... How is a state update put in the first place? It seems just sitting there doing nothing ...
And now I understand your question. Are you curious how put (and get ) work?
Maybe an example in JavaScript will help (a language with actual mutable state):
var s; // mutable state function get() { return s; } function put(x) { s = x; } function tick() { var n = get(); put(n + 1); return n; }
Hopefully this illustrates that although n does not change, the internal state will still be updated. If you execute tick() twice, the state will increase twice.
To return to Haskell, here is the full definition of the (relevant parts) of the State monad:
newtype State sa = State { runState :: s -> (a, s) } instance Monad (State s) where return a = State $ \s -> (a, s) m >>= k = State $ \s -> let (a, r) = runState ms in runState (ka) r get = State $ \s -> (s, s) put s = State $ \_ -> ((), s)
Now try expanding your tick example again by manually entering >>= , return , get and put . I hope you will understand how the state works.
Tom lokhorst
source share