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 :-) 

2 comments:

Sandeep Kanabar said...

Hey Lakshmi.. after a loong time.. Back with a new basket full of Haskells??

Wonder how you stumbled upon Haskell? Will you spill the beans sir ji?

Lakshmi said...

@Sandy

If you don't write any useful code, you develop a hatred and start to dislike the one you are currently doing. ;-) jokes apart.

sometime back (2 yrs back), Veeru and i experimented something in Scala and during that time i remember reading an article about Scala being possible replacement for Java.

Of late, i felt like i should learn something new that improves my thinking and also challenge me. Obviously, heard that FP is quite a challenge to learn and so picked up nice little Haskell book.