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

后端 未结 1 845
离开以前
离开以前 2021-01-21 23:13

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

1条回答
  •  盖世英雄少女心
    2021-01-22 00:07

    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)
    

    0 讨论(0)
提交回复
热议问题