Question

I want to implement put with modify

    put :: s -> m ()
    modify :: (s -> s) m s

when i do

    put s = modify $ const((), s)

i get the error,
Expected type: m ()
Actual type: m ((), s)
I have tried something like this

    modify $ const((), s) >>= \x -> return (fst x)

to get the expected type m()
but this solution does not work

could someone explain to me how you can implement put by using modify?
Thank you for your time and help.

Was it helpful?

Solution

modify has type

modify :: (MonadState s m) => (s -> s) -> m ()

The first argument is a plain s -> s function which modifies the state. So, while you are on the right track by trying to use const, you don't have to put the state in a tuple:

put s = modify $ const s

Note that, while you can define put in terms of modify, that means you won't be able to give a general definition of modify; rather, you have to do it for each concrete monad which is an instance of MonadState. That explains why, in Control.Monad.State, get and put are class methods of MonadState: how you implement them depends on the specific state monad. modify, then, is defined in terms of get and put.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top