Archive for Dezember 2008

Haskell Heureka

Dezember 23, 2008

Now here is one of the many discoveries I got with the Haskell programming language. Haskell is a functional programming language that might look occult or opaqe to the average programmer. You might wonder how you get anything done in this language. But I recently had some mind-blowing experiences. Now if you are not a haskell programmer be warned: You might not understand what I’m talking about unless you have a basic understanding of the language. To the more enlightened master hacker haskell guys: This might seem trivial to you but here is what I discovered:

I had a task at hand which required to sequence some monadic operations of the form (a -> m a). It was the IO Monad to be specific but it doesn’t matter because it works with any Monad. The function I wrote had the following type signature:
m a -> [a -> m a] -> m a
It did some kind of sequencing of functions in a list so I called it mapseq, which might not be the best name for the function but was close enough. Here is the definition:

mapseq :: Monad m => m a -> [a -> m a] -> m a
mapseq f [] = f
mapseq s (f:fs) = mapseq (s >>= f) fs

In the back of my mind I always knew that it should be somehow transformed into a fold function, but I could not quite define it, maybe because I tried with foldr too much. The solution was simple but it struck me as both cool and elegant:
foldl (>>=)
That’s all. It has the same type and the same semantics as mapseq and it replaces my crude function entirely. Heureka!