Where is the data constructor for 'State'?

后端 未结 3 1059
无人共我
无人共我 2021-02-12 07:32

After reading a couple of tutorials on Haskell state monads I wanted to try them out myself. The tutorials I read claim that the Control.Monad.State provide the following defini

3条回答
  •  爱一瞬间的悲伤
    2021-02-12 08:08

    I am working through Learn You A Haskell (LYAH), and I thought that I would post the working version of the example code found at http://learnyouahaskell.com/for-a-few-monads-more#state (Chapter 13, Section "Tasteful stateful computations")

    The code that no longer works:

    import Control.Monad.State  
    
    pop :: State Stack Int  
    pop = State $ \(x:xs) -> (x,xs)  
    
    push :: Int -> State Stack ()  
    push a = State $ \xs -> ((),a:xs)  
    

    The code modified to work:

    import Control.Monad.State 
    
    pop :: State Stack Int
    -- note the change from "State" to "state"
    pop = state $ \(x:xs) -> (x,xs)
    
    push :: Int -> State Stack ()
    push a = state $ \xs -> ((), a:xs)
    

    The "stackManip" function works as is:

    stackManip :: State Stack Int  
    stackManip = do  
        push 3  
        a <- pop 
        pop 
    

提交回复
热议问题