The Gee-Whiz Monad (I)

19Feb07

[] is really the gee-whiz monad. Haskell code that prints *all the five-number combinations of integers in [-5..5]:


mapM (\x->[x+i | i<-[-5..5]]) [1..5]

No, really, try it. This has to qualify as the “most surprisingly long output” line of code in all of computer programming.



3 Responses to “The Gee-Whiz Monad (I)”

  1. 1 Pseudonym

    factorial n = genericLength $ mapM (\x -> [() | i <- [0..x]]) [0..n-1]

  2. 2 Jules Bean

    That doesn’t quite generate what you think it does. You want the simpler:

    mapM (\x -> [-5..5]) [1..5]

    or possibly (if you find this clearer)

    mapM (const [-5..5]) [1..5]

    This represents the underlying ‘every combination of possibilities’ semantics of the list monad, in which actions can return more than one result.

    Another expression of it is:

    sequence (replicate 5 [-5..5])

    …arguably more straightforward. sequence makes it explicit that the computations don’t affect each other. mapM leaves that possibility open, but then the fact the actions are all ‘const’ actions (they don’t use the x in \x) shows that, in fact, they are independent.

  3. You make a number of nice points with this text however its robust in my view to concentrate on the article


Leave a comment