I\'m a beginner at Haskell and I\'ve come across a situation where I would like to use the state monad. (Or at least, I think I that\'s what I\'d like to use.) There are a milli
First you need to convert your existing functions to return State Machine a
values:
import Control.Monad.State.Lazy
data Machine = Register Int
addToState :: Int -> State Machine ()
addToState i = do
(Register x) <- get
put $ Register (x + i)
subtractFromState :: Int -> State Machine ()
subtractFromState i = do
(Register x) <- get
put $ Register (x - i)
getValue :: State Machine Int
getValue = do
(Register i) <- get
pure i
then you can combine them into a stateful computation:
program :: State Machine Int
program = do
addToState 6
subtractFromState 4
getValue
finally you need can run this computation with evalState
to get the final result and discard the state:
runProgram :: Int
runProgram = evalState program (Register 0)