[Haskell-cafe] do

Luke Palmer lrpalmer at gmail.com
Sat Oct 13 17:28:48 EDT 2007

On 10/13/07, PR Stanley <prstanley at ntlworld.com> wrote:
> Hi
> "do", what's its role?
> I know a few uses for it but can't quite understand the semantics -
> e.g. do putStrLn "bla bla"
> So, what does do, do?

In this example, do doesn't do anything.  do doesn't do anything to a
single expression (well, I think it enforces that its return value is
a monad...).  It's only when you give it multiple expressions that it
"rewrites" them into more formal notation.  For example:

    do putStrLn "bla"
       putStrLn "blah"

Will be rewritten into:

    putStrLn "bla" >> putStrLn "blah"

It introduces a block of "sequential actions" (in a monad), to do each
action one after another.  Both of these (since they're equivalent)
mean print "bla" *and then* print "blah".

do also allows a more imperative-feeling variable binding:

    do line <- getLine
       putStr "You said: "
       putStrLn line

Will be rewritten into:

    getLine >>= (\line -> putStr "You said: " >> putStrLn line)

Looking at the do notation again: execute getLine and bind the return
value to the (newly introduced) variable 'line', then print "You said:
", then print the value in the variable line.

You can think of the last line in the block as the return value of the
block.  So you can do something like:

    do line <- do putStr "Say something: "
       putStr "You said: "
       putStrLn line

In this example it's kind of silly, but there are cases where this is useful.


More information about the Haskell-Cafe mailing list