[Haskell-beginners] Monad operators: multiple parameters

Daniel Fischer daniel.is.fischer at googlemail.com
Tue Jun 7 14:43:09 CEST 2011


On Tuesday 07 June 2011, 14:30:29, Christopher Howard wrote:
> In a reply to an earlier question, someone told me that "do" expressions
> are simply syntactic sugar that expand to expressions with the >> and
> 
> >>= operators. I was trying to understand this (and the Monad class)
> >>better.
> 
> I see in my own experiments that this...
> 
> main = do ln1 <- getLine
>           putStrLn ln1
> 
> translates to this:
> 
> main = getLine >>= \ln1 -> putStrLn ln1

Shorter: getLine >>= putStrLn

An expression `\x -> foo x' is equivalent to `foo', using a lambda doesn't 
make things clearer in such cases, only if something more complicated is 
done with the argument(s).

> 
> However, what does this translate to?:
> 
> main = do ln1 <- getLine
>           ln2 <- getLine
>           putStrLn (ln1 ++ ln2)

That desugars via

getLine >>= \ln1 -> (do { ln2 <- getLine; putStrLn (ln1 ++ ln2); })

to

getLine >>= \ln1 -> (getLine >>= \ln2 -> putStrLn (ln1 ++ ln2))

Note that the outer parentheses aren't necessary.

do val <- foo
   bar
   baz val

desugars to

foo >>= \val -> do { bar; baz val; }

and the you can desugar the right hand side recursively.



More information about the Beginners mailing list