Getting started with Haskell

December 3rd, 2007 posted by codders

All the cool kids, it seems, are using Haskell these days. Or at least, the two or three people with whom I talk about software on a regular basis. Functional programming is fun. It makes you think a little differently about the world, and serves as a decent substitute for a unicorn chaser if you’ve been writing PHP all day.

I remember almost the first snippet of code we saw on our computer science course was the following to count the number of items in a list:

count [] = 0
count (x:xs) = 1 + count(xs)

which, for a guy who’d only ever really written code in BASIC before starting the course, was a bit of an eye opener. I think it was probably three or four lectures in before we had to work out the code for printing out all the permutations of a list:

> permute [1,2,3]
[[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]

After much blood, sweat, and tears we’d eventually come to the realisation that:

insert x [] = [[x]]
insert x (y:ys) = (x:y:ys) : map (\z -> y:z) (insert x ys)

permute [] = [[]]
permute (x:xs) = concat (map (insert x) (permute xs))

would suffice (where concat flattens a list and map has the usual meaning). At first glance, it all looks pretty daunting, but after a while one comes to understand what it means for the type of map to be (a -> b) -> [a] -> [b], and starts to appreciate the compact elegance of the code that’s produced in functional programming.

Ugly implementation details? You betcha…

apt-get install hugs
apt-get install haskell98-tutorial
cat > hello.hs <<END
#!/usr/bin/runhugs +l
main :: IO()
main = putStr "Hello World!\n"
END
chmod 755 hello.hs
./hello.hs

(N.B. hugs with the ‘+l’ switch is sensitive about filenames. Non ‘.hs’ files require lines of Haskell to begin ‘>’). It’s often more comfortable to develop these things interactively. Booting into a hugs session and typing

> :load hello.hs

will import the functions defined in hello.hs into your session.

Over the coming weeks, I hope to be honing my skills and infuriating my coworkers by replacing bits of critical infrastructure with Haskell scripts. I’ll let you know how that goes.