David Banas | 29 Dec 03:24 2013
Picon

Question on nested State monads.

Hi all,

If I want to use a second, nested State monad inside another State monad, must I thread the outer monad’s
state through the processing of the inner one, even if the inner one falls out of scope before I return from
the processing body of the outer one?

Thanks,
-db
lucas di cioccio | 29 Dec 09:25 2013
Picon

Re: Question on nested State monads.

Hi David,
If I want to use a second, nested State monad inside another State monad, must I thread the outer monad’s state through the processing of the inner one, even if the inner one falls out of scope before I return from the processing body of the outer one?

In short: yes you can nest StateT and to access the "inner parts" you need to lift the get/put/modify functions. The Real-World Haskell book has an example for stacking monad transformers of a same TypeClass (cf. http://book.realworldhaskell.org/read/monad-transformers.html "When explicit lifting is necessary".)

The first time, it's best to convince yourself by writing down the types of lifted put/get.

Best,
--Lucas
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
Albert Y. C. Lai | 29 Dec 16:26 2013
Picon

Re: Question on nested State monads.

On 13-12-28 09:24 PM, David Banas wrote:
> If I want to use a second, nested State monad inside another State monad, must I thread the outer monad’s
state through the processing of the inner one, even if the inner one falls out of scope before I return from
the processing body of the outer one?

I do not know what the whole sentence "must I ... the outer one" is 
talking about. But why don't you go scientific and use concrete 
experiments to find out? Here is a starter:

import Control.Monad.State

main = print answer

answer :: (Bool, Char)
answer = evalState (evalStateT program True) 't'

program :: StateT Bool (State Char) (Bool, Char)
program = do
     bool <- get
     char <- lift get
     return (bool, char)

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Gmane