Haskell MonadState Class
MonadState is a typeclass for computations that can read and change a state value. Any stack with state can provide its operations.
Get returns the current state
Get returns the state given to runState. The value and the final state are both 7.
import Control.Monad.State
main :: IO ()
main = print (runState get 7)Modify changes the state
Modify triples the state. Tripling 4 gives 12.
import Control.Monad.State
main :: IO ()
main = print (execState (modify (* 3)) 4)Put then get shows the new state
Put replaces 0 with 3, so the next get returns 3. The pair shows value and state.
import Control.Monad.State
main :: IO ()
main = print (runState (put 3 >> get) 0)Example
import Control.Monad.State
computation :: State Int Int
computation = do
modify (+ 2)
modify (* 3)
get
main :: IO ()
main = print (runState computation 4)Key points
- Get: get returns the current state value.
- Put: put replaces the state value with a new value.
- Modify: modify applies a function to the state value.
- Threading: each operation sees the state left by the previous operation.
- Reuse: the same state code works in State and in a larger stack.
In this example, modify adds 2 to 4 to give 6, modify triples 6 to give 18, and get returns 18.
Note
get does not change the state, it only reads it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does runState (modify (+ 1) >> get) 41 return?