I've tried to learn Haskell in the past and found it completely horrible to look at. That was, until I got around to learning Scheme and decided to look deeper into it.

A couple of nights ago a friend showed me a small piece of Haskell code which reads a series of lines formatted like this:

a 1
b 2
c 3

And sums up the second column. The code looks like this:

foldl1 (+) (map (\c -> read (c !! 1)) (map words (lines "a 1\nb 2\nc 3")))

At first glance, I was at a total loss as to what was going on. So I fumbled around in ghci for a while figuring out what each part was doing.

It took me a while to realise that both words and lines are builtins, and this alone cleared the picture up quite significantly.

The other part I had major trouble with was the !!, and google was somewhat unhelpful at first, but it is basically the Haskell equivalent of (list-ref c 1) aka the array subscript operator.

Now it's starting to come together in my head. The line basically reads as (from right to left):

Split the string a 1\nb 2\nc 3 into a list of lines, and then for each of the lines, split the line into separate words. Now, for each of these lines, create a lambda that reads the list of words in the line, and "read" the second item (this causes the string "1" to become the integer 1) and return it. Finally, now that we have a list of integers, Fold them to the left using the "+" function. The result is 6.

The translation into Scheme is quite easy too, if we define a couple of small helper functions:

(define read/s (lambda (c) (with-input-from-string c read)))
(define words string-split)
(define lines (lambda (str) (string-split str "\n")))

; Now the actual translation (which has the same number of characters as the Haskell version!)
(fold + 0 (map (lambda (c) (read/s (second c))) (map words (lines "a 1\nb 3\nc 3"))))

Just understanding this small piece of Haskell has made me curious about using it further. The idea that originally drove me away from it (the conciseness, which makes it hard to read at first), turns out to be its simplicity. Much the same as with Scheme.

(Maybe) Related posts: