[Haskell-cafe] trying to understand monad transformers....
Paul Johnson
paul at cogito.org.uk
Tue Sep 9 14:15:48 EDT 2008
Daryoush Mehrtash wrote:
> The MaybeT transformer is defined as:
> newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe> a)}
>
>
> instance Functor <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor> m => Functor <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor> (MaybeT m) where
>
> fmap <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap> f x = MaybeT $ <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:.> fmap <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap> (fmap <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap> f) $ <http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:.> runMaybeT x
>
>
> ....
>
>
> Question: What does "runMaybeT x" mean?
>
All monads (except IO) have a "run" function. E.g. "runST" for the ST
monad, "runState" for the state function, and so on. A monadic action
is actually a function that (typically) takes extra arguments and
returns extra results. In the monadic action form these extra data are
hidden, and its up to the monad "bind" function to thread them from one
action to the next. The "runX" function for some monad X converts a
monadic action into the underlying function with that data exposed. In
most cases the monad is defined as a "newtype" wrapper around the
function, so the "run" function is just the inverse of the constructor.
In the case of a monad transformer the result of the function is not a
value, its an action in another monad. Thats what you see in the case
of MaybeT. A MaybeT action is actually a monadic action that itself
returns a Maybe value. So you use "runMaybeT to turn your MaybeT action
into an action in the inner monad, and then run that action using its
"run" function to finally get a Maybe result.
Make sense?
Paul.
More information about the Haskell-Cafe
mailing list