[Haskell-cafe] do

PR Stanley prstanley at ntlworld.com
Sat Oct 13 19:15:29 EDT 2007


Thanks for the very clear explanation. More questions:
What is the role of ">>"?
How is ">>" different to ">>="? I am aware that ">>=" is used for 
sequencing parsers but that's all I know about it.
Thanks, Paul

At 22:28 13/10/2007, you wrote:
>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: "
>                   getLine
>        putStr "You said: "
>        putStrLn line
>
>In this example it's kind of silly, but there are cases where this is useful.
>
>Luke



More information about the Haskell-Cafe mailing list