I’ve written a whole lot of exercises now on functions that use State, like
addStateAndReturnResult :: Int -> State Int Int
addStateAndReturnResult x = do
state <- get
put $ state + x
return $ state + x
But I have no idea how to actually call the function and get the result out. Something like this gives me a weird type error that is not even close:
callIt :: Int
callIt = addStateAndReturnResult 3 (State 1)
How do I make function run please?
>Solution :
There are three functions for this.
The most general is runState :: State s a -> s -> (a, s). It returns a tuple of the last state and the final return value.
Then there is evalState :: State s a -> s -> a which just returns the final return value.
And there is execState :: State s a -> s -> s which just returns the last state value.
In your case, you probably want evalState:
callIt = evalState (addStateAndReturnResult 3) 1