[Haskell-cafe] StateT and modify

Cale Gibbard cgibbard at gmail.com
Wed Nov 8 06:01:09 EST 2006


bar = do
   x <- get
   y <- lift $ myAdd 1 x
   put y
   return y

If you want, you can write something which captures this idiom:

liftModify c = do
    x <- get
    y <- lift (c x)
    put y

and then use that like:

bar = do
   liftModify (myAdd 1)
   get

On 08/11/06, Peter Steiner <pnsteiner at gmail.com> wrote:
> hi haskellers,
>
> i have a basic question regarding StateT encapsulating IO and the
> modify function.
>
> my scenario is similar to the following simple code snippet:
>
> > import Control.Monad.State
> >
> > type MyState = StateT Int IO
> >
> > test = evalStateT foo 0
> >
> > foo = do
> >    modify $ (+) 1
> >    get
>
> i would like to be able to debug what's happening inside the modifier
> function. that's why i want to be able to use a modifier that's in the
> IO monad, like in the following, obviously defunct snippet:
>
> > test = evalStateT bar 0
> >
> > bar = do
> >    modify $ myAdd 1
> >    get
> >
> > myAdd :: Int -> Int -> IO Int
> > myAdd x y = do
> >    putStr "in myAdd\n"
> >    return $ x + y
>
> this fails because (myAdd :: Int -> Int -> IO Int) does not match the
> required modify argument type (Int -> Int -> Int) for MyState.
>
>     Couldn't match expected type `Int' against inferred type `IO Int'
>     In the second argument of `($)', namely `myAdd 1'
>     In the expression: modify $ (myAdd 1)
>     In a 'do' expression: modify $ (myAdd 1)
>
> is it possible to 'lift' StateT modify into the inner monad (IO in my case)?
>
> regards,
> peter.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list