Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a Haskell State function?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading