23 July 2011

First Program in Haskell

Recently, I stumbled upon a new programming paradigm - functional programming. Rather than focusing on variables, we define functions that does something. Without much of theory, let us quickly see an example

Write a program that finds triplets (a, b c) such that a, b and c are sides of a right angle triangle with none of the sides is greater than 20. I tried to write programs in Java and in Haskell as well. Here is the code snippet
Java
public class RightAngleTuples {
public static void main(String[] args) {
printTuples();
}
public static void printTuples() {
for(int c = 1; c <= 10; c++) {
for(int a = 1; a <= c; a++) {
for(int b = 1; b <= a; ++b ) {
if(a*a + b*b == c*c && a+b+c == 24) {
System.out.println(a + ", " + b + ", " + c);
}
}
}
}
}
}
Haskell
 Prelude> let triples = [(a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24 ]
Prelude> triples
[(8,6,10)]
Initially it may appear that both the programs are different syntactically. But if you really see, while programming in an imperative languages, we need to think a lot of logic and variables (or memory location) that maintains the state of the program. It is programmers responsibility to keep the state sane. But in the case of functional programming, there is no concept of state. Everything is functions (obviously everything is logic).

If you are really interested to learn a new programming paradigm, i recommend Haskell. With my few hours of encounter with Haskell, i feel it changes one's thinking :-) and Learn you a Haskell for Great Good by Miran Lipovaca can be a great resource. (BTW, i copied the above example from the book and i promise that it is in fact last example that i will steal from the book). An heads-up: reading Haskell doesn't increase your value in job market :-), you cannot ask for 40% more hike but just improves your geeky quotient :-)

More stuffs on Haskell in coming weeks/months. Sharing never hurts :-)