[Haskell-cafe] Re: Can we come out of a monad?
Anton van Straaten
anton at appsolutions.com
Fri Jul 30 07:49:32 EDT 2010
Kevin Jardine wrote:
> As a Haskell newbie, the first thing I learned about monads is that
> they have a type signature that creates a kind of mud you can't wash
There are places where you can't wash it off, and places where you can.
> f :: String -> MyMonad String
> By mentioning the monad, you get to use its special functions but as a
> hard price, you must return a value with a type signature that locks
> it within the monad
That's perfectly correct: "you must return a value with a type signature
that locks it within the monad." That's because you're referring here
to returning a value from a monadic function with a return type of
MyMonad String. But that's just one part of the picture.
Consider a caller of that function: after applying f to some string, it
ends up with a value of type MyMonad String. One of the things you can
typically do with such values is "wash off the mud" using a runner
function, specific to the monad.
They're called runners (informally) because what they do is run the
delayed computation represented by the monad. In the case of the State
monad, the runner takes an initial state and supplies it to the monad in
order to start the computation. If these runners didn't exist, the
monad would be rather useless, because it would never actually execute.
The result of running that computation typically eliminates the monad
type - the mud is washed off.
You can even do this inside a monadic function, e.g.:
g m = do s <- get
let x = evalState m s -- wash the mud off m !
But the value of x above will be locked inside the function - you can't
return such values to the caller without using e.g. "return x", to
return a monadic value.
So you may be able to wash the mud off a monadic value, but if you want
to pass that value outside a monadic function you have to put the mud
back on first.
However, if you have a monadic value *outside* a monadic function, no
such rule applies.
> The more I learn about monads, however, the less I understand them.
> I've seen plenty of comments suggesting that monads are easy to
> understand, but for me they are not.
Monads are very general, which means they're not easily learned by the
common style of extrapolating from examples. They're easy to understand
in hindsight though! :-}
More information about the Haskell-Cafe