[Haskell-cafe] The State Monad

John Goerzen jgoerzen at complete.org
Thu Oct 7 18:56:25 EDT 2004


This thing is giving me fits.  I need a global variable of sorts for an
implementation of Syslog.  (Yes, I really do.)

It seems the right way to do that is the state monad.  But I can't
figure out how to do two simple things:

 * Read what is in there without modifying it

 * Modify it appropriately

I looked at the examples in Control.State.Monad.  We see:

 tick :: State Int Int
 tick = do n <- get
           put (n+1)
           return n


Add one to the given number using the state monad: 

 plusOne :: Int -> Int
 plusOne n = execState tick n

Which looks nice enough, but completely useless.  tick seems to be a
very complex way to say ((+) 1) in this example.  Oddly enough, I get a
type error if I try this:

tick :: Int -> State Int Int
tick newval = do put newval
                 return newval

Or this:

tick :: State Int Int
tick = do n <- get
          return n

That is even more incomprehensible to me -- why would removing a line
before the return cause a type error?




More information about the Haskell-Cafe mailing list