[Haskell-cafe] State Monad
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
> 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
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) ()
str <- liftM get
a <- get
let (a', str') = trans (a, str)
liftM (put str')
Alternatively, you can use the ordinary state monad with (a,String) as its
state. Then modifyT is just modify.
More information about the Haskell-Cafe