[Haskell-beginners] What is a "Monad Comprehension" ?

Michael Orlitzky michael at orlitzky.com
Mon Apr 7 13:05:42 UTC 2014


On 04/07/2014 04:33 AM, John M. Dlugosz wrote:
> I know about List Comprehensions, but what is a general Monad Comprehension?  List 
> Comprehensions are the use of set-builder notation to define a list, so I don't understand 
> how that would generalize.

The set-builder notation to find the sums of elements from two lists
looks like,

  list_sums = [ x + y | x <- [1,2,3], y <- [4,5,6] ]

The way the list monad is defined, this is the same thing as,

  list_sums = do
    x <- [1, 2, 3]
    y <- [4, 5, 6]
    return (x + y)

The set-builder notation is not obviously generalizable, but once you
desugar it to do-notation, it's more clear that you could do the same
thing with any monad. What actually happens might not be intuitive, but
the desugaring will work at least. For the Maybe monad, you could do
something like,

  maybe_sums = [ x + y | x <- Just 1, y <- Just 2 ]

which will be desugared into,

  maybe_sums = do
    x <- Just 1
    y <- Just 2
    return (x + y)

Any other monad will work the same.



More information about the Beginners mailing list