haskellstate-monad

Convert State Int to Int


I am trying to implement a counter and I'd like to convert something of type State Int to Int, so I can add it to a variable. Can somebody help me develop an auxiliary function to perform this cast?

I have been stuck on this for a while now, because I am not very used to working with monad State.


Solution

  • Use execState to run the stateful action and obtain the final state:

    execState :: State s a -> s -> s
    

    For example, incByOne increments the counter by one:

    incByOne :: State Int ()
    incByOne = modify (+1)
    

    Then, if you use the execState monad runner with the initial state of 7:

    main :: IO ()
    main = do
      let initialCount = 7
      let count = execState incByOne initialCount
      print count
    

    It will print 8