[Haskell-cafe] State Monad
Wolfgang Jeltsch
wolfgang at jeltsch.net
Wed Mar 3 15:03:58 EST 2004
Am Mittwoch, 3. März 2004 14:44 schrieb Georg Martius:
> [...]
> Now I have also functions to map from (a, String) -> (a,String). I could
> write:
>
> modifyT :: ((a, String) -> (a, String)) -> a -> State String a
> modifyT trans a = do str <- get
> let (a', str') = trans (a, str)
> put str'
> return a'
>
> f :: State String ()
> f = do put "hallo"
> modify strTrans
> i <- modifyT strIntTrans 4
> -- strIntTrans :: (Int, String) -> (Int, String)
> i' <- modifyT strIntTrans i
> ...
> But this is obviously awkward. How can I stick two Monads in each other? I
> could't figure out how to use StateT.
StateT is one solution. See
http://www.haskell.org/pipermail/haskell/2004-January/013330.html
and the follow-ups (available via the "next message" links). With StateT,
modifyT may be written as follows (untested code):
modifyT :: ((a, String) -> (a, String)) -> StateT a (State String) ()
modifyT trans
= do
str <- liftM get
a <- get
let (a', str') = trans (a, str)
liftM (put str')
put a'
Alternatively, you can use the ordinary state monad with (a,String) as its
state. Then modifyT is just modify.
> [...]
> Thanks!
> Georg
Wolfgang
More information about the Haskell-Cafe
mailing list