[Haskell-beginners] Re: = vs <-

Ertugrul Soeylemez es at ertes.de
Fri Aug 13 20:06:23 EDT 2010

Kyle Murphy <orclev at gmail.com> wrote:

> Remember that in most cases, once something is "inside" of a monad (IO
> in this case), it's very difficult, impossible, to get it out again.

I think, this is very misleading.  You never get "out of a monad", you
get "into" it, and you can do that whenever you want.  Remember that the
monadic world is inside of the pure world, not the pure world inside of
the monadic world.  In fact, the monadic world is part of it.

The name bound by '<-' is something you can refer to in the pure world.
There is nothing difficult about using the result of a monadic
computation in the pure world.  Just give it a name and refer to it, and
that's it.

> The do syntax just adds a convenient abstraction so that you don't
> have to construct complex chains of >>= and >> operations by hand. In
> our limited example this is fairly trivial, but consider something
> like:
> main = do
>   something <- foo
>   blah <- bar something
>   moreblah <- baz something blah
>   putStrLn moreblah
>   putStrLn "really long chain now"

Pretty straightforward:

  main =
    foo >>= \something ->
    bar something >>= \blah ->
    baz something blah >>= \moreblah ->
    putStrLn moreblah >>
    putStrLn "really long chain now"

> which would be translated to:
> main = foo >>= (\something -> bar something >>= (\blah -> baz
> something blah >>= (\moreblah -> putStrLn moreblah >> (putStrLn
> "really long chain now"))))

You could just as well write:

  main = do { something <- foo; blah <- bar something;
    moreblah <- baz something blah; putStrLn moreblah; putStrLn
    "really long chain now" }

You are complicating things artifically.  For example there is no reason
to have all those parentheses, because (>>=) is associative by

The do-notation doesn't make nasty things nice.  It makes nice things
nicer.  Don't be afraid to use raw monadic combinators, because
sometimes they are much better:

  main = getArgs >>= mapM_ (readFile >=> putStr)

Much more concise than:

  main = do
    files <- getArgs
    forM_ files $ \file -> do
      content <- readFile file
      putStr content


nightmare = unsafePerformIO (getWrongWife >>= sex)

More information about the Beginners mailing list