Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help me to understand the concept of inner and outer monads

Tags:

haskell

monads

I'm not a monad-jedi yet, but I have a basic understanding of them.

Now I read some articles mentioning the 'inner' and 'outer' monad and I wonder what that means.

(Links to) code examples will be helpful.

Thanks!

like image 598
cies Avatar asked Mar 24 '12 17:03

cies


1 Answers

A lot of Haskell applications use monad transformers, which are instances of the type class

class MonadTrans t where
    lift :: Monad m => m a -> t m a

What this does is allow you do combine the environment provided by several monads, by wrapping them together. For example, the State s monad gives you the ability to operate on state of type s that is automatically threaded through your computation, while the Maybe monad lets you short circuit failure. But if you want both of those effects, then you can combine them by using a monad transformer version of one of the two, such as:

something :: StateT s Maybe a

Here, StateT is defined in the mtl package, and is similar to State except for leaving a place for another monad that sit inside of it. By using monad transformers like this, you can compose the effects from several monads in a piecemeal fashion.

In this case, Maybe is the inner monad, and StateT s Maybe is the outer monad. You can get from the inner monad to the outer monad by using lift from the MonadTrans type class.

like image 197
Chris Smith Avatar answered Oct 25 '22 19:10

Chris Smith