Search code examples
haskellstate-monad

State where the resulting state is the argument provided and the value is unit


Exercise 23.8.2 in the haskell book asks me to construct a state like the following:

put' :: s -> State s ()
put' s = undefined
-- should act like:
-- Prelude> runState (put "blah") "woot"
-- ((),"blah")

The only implementation I have gotten to typecheck is

import Control.Monad.Trans.State -- Not sure this is the right import
put' :: s -> State s ()
put' s = state $ \s -> ((), s)

But this returns the state in the argument of runState, not put':

λ> runState (put' "blah") "woot"
((),"woot")

What haskell acrobatics do I need to fix this? Do not see how I can access the "blah".


Solution

  • put' s = state $ \s -> ((), s)
         ^            ^
    

    You reused the variable s for two different bindings. Try using a different name, and the solution will be obvious ;-)

    By the way, you should enable warnings using the -Wall flag in GHC / GHCi. This would have pointed out that you have defined s twise, and the second binding shadows the first one.