How can I write this simple code using the state monad?

人走茶凉 提交于 2019-12-01 23:43:44
Lee

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!