03 July 2014
I've been learning Haskell for about two weeks now and I'm hooked. On one hand, it feels difficult, because of so many new concepts like pattern matching, recursion, the multitude of types, but these are things that also make me love it. Pattern matching feels so much more elegant than using if clauses, especially when used with recursion. For example the definition of the map function would be:
map :: (a -> b) -> [a] -> [b] map f  =  map f (x:xs) = f x : map f xs
For those who don't know, the map function takes a function and a list and applies the function to each element of the list returning a new list. That's what the type declaration says, above the function definition. After the type declaration, the first line handles the edge case when the list is empty. In that case, the function returns an empty list, of course. The second line shows pattern matching against a list. (x:xs) assign the first element of the list to x and the rest to xs. : is an operator that inserts the left side argument into the right side list. So the second line calls the function f on the first element of the list and inserts it at the beginning of the list returned by map f xs.
Another very cool thing is that every function supports partial application or currying. For example:
ghci> let add x y = x + y ghci> let add3 = add 3 ghci> add3 5 8
When we apply add to 3, a new function is returned which expects only one argument. When it is called with that argument, it returns the value. Another very cool thing is that operators are functions in Haskell. That means that you can do:
ghci> map (+3) [1..5] [3,4,5,6,7,8]
When you want to use an operator as a function, you surround it with parentheses. This is called a section. So, what did we do above? We applied the (+) function to 3. Because (+) expects two arguments and we only passed it one, (+3) returned a new function which expects an argument. Using map we applied that function to all the elements of the list.
Then there are type classes which are kinda' like interfaces in OO languages. Overall, it feels like there are so many abstractions in Haskell which makes things a bit harder to grasp. At the same time, the language has an elegance to it that makes me like it a lot. I'm looking forward to exploring more and actually writing software in Haskell.