Functional programming with Haskell
At the Lima (PerĂº, not Ohio) Developer Days somebody told me "Ah, you're the funny languages guy". I had to smile and explain that aspect of my life: at college I had a teacher who had a penchant for LISP, being young thus impressionable I acquired the taste for lists and functional programming. Years later I discovered Haskell and when I have a little spare time *and can't be outdoors* I like to play with this nice little language. A small sample:
Before explaining the qsort function, let's discuss some of its uses (and the use of lists in Haskell):
- [2,500,-1,8,6,2000] is a six integers list (duh)
- Note that qsort works also with strings, by the way it's not that Haskell hasn't got strong typing but rather that it's got just-in-time type inference
- reverse is a predefined function that, well, reverses a list (in this case the list that results from applying qsort). Parenthesis are necessary as (reverse qsort) is not possible (reverse applies to lists not to functions, but note that Haskell can actually apply functions to functions)
- [49,47..1] expands to the list of all odd numbers between 49 and 1, note how Haskell infers the sequence. ++ is the list concatenation operator.
Now, let's dissect the qsort function:
- qsort [] = [], ordering an empty list gives... an empty list
- qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs), ordering a list that start with x followed by xs (the list of all items behind x) is the same as:
- Taking all elements lower than x ( filter (< x) xs ) and ordering them (using qsort itself of course)
- Putting [x], that is the list with x as its sole element, in the middle
- Taking all elements greater or equal to x ( filter (>= x) xs ) and qsorting them
Compact and easy to understand (once you are comfortable with the syntax). Now that is in vogue to explore alternative languages like Python or Ruby, giving a look to Haskell or his functional relatives wouldn't be a bad idea. You will find a short and engaging introduction to Haskell here. Alas, for my examples I use WinHugs, a Haskell interpreter that runs on Windows, very handy for experimenting with the language (the latest version, May 2006, is fresh from the oven).