Diving into Haskell

Haskell has been, for a number of years, a language that I have always wanted to dive into. I’ve heard it lauded as the language of “true hackers”, and it’s somewhat of a sign that you’ve made it as a developer if you can make sense of its terse syntax and seemingly arcane concepts. No mutation? No for-loops? What?! How do you get anything done in the language if it doesn’t have these most basic of control flow mechanisms?

Well, the other day I saw the following snippet as a way of generating the Fibonacci sequence in Haskell:

fibonacci = 1 : 1 : zipWith (+) fibonacci (tail fibonacci)

and I immediately knew that I needed Haskell in my life. I didn’t even fully understand it on first glance; at that point all I knew about Haskell was that spaces were used for function application, rather than the more traditional (), but already I could see the outline of what the solution meant. The Fibonacci sequence is defined as 1, 1, then the sum of the previous number with the one before that, recursively. But that’s exactly what the above code says. Even to the relatively untrained eye (mine) we can kind of see that the code is telling us to start with two 1’s, then mash together the sequence we are currently building with itself (dropping the first element) using + as the “mashing operator”.

Let’s contrast this to a least-effort implementation in Python that generates the same sequence:

def fibs():
    x = y = 1
    yield y
    while True:
        yield x
        x, y = x + y, x

This is, in my opinion, much harder to read than the Haskell version. I’m not exactly sure why; maybe it’s because the Haskell version is so terse that you can hold it all in your mind’s eye at once, or maybe it’s got something to do with the way our brains process recursion vs. mutating values. In any case this example was enough to hook me.

I devoured the sublime “Learn you a haskell for great good” in the space of about a week, although I’m sure it will take a while before I fully digest the meaning of, e.g., functors and applicative functors (even if the mathematical definition is trivial). I think it’s a testament to the quality of the exposition of this book that I was left with the distinct impression of having “got” monads after only a few readings (although I’m probably way off the mark). I’m not going to fall into the “monads are like burritos” trap, though; as far as I can tell, they appear to be just a particularly useful design pattern, and I am by far not the first person to draw this conclusion.

My next step in Haskell is going to be to tackle a small project of very limited scope, to see if I can write anything beyond tutorial code; should be fun!