州monad和learnyouahaskell.com

Und*_*ren 12 monads haskell

我正在阅读关于状态monad的Learn You a Haskell指南,但我无法理解它,因为堆栈示例无法编译.在指南中,他使用了以下代码:

import Control.Monad.State  

type Stack = [Int]

pop :: State Stack Int  
pop = State $ \(x:xs) -> (x,xs)  

push :: Int -> State Stack ()  
push a = State $ \xs -> ((),a:xs) 
Run Code Online (Sandbox Code Playgroud)

虽然我理解它应该做什么,但它不会编译.我不知道为什么.错误消息是:

Stack.hs:6:7: Not in scope: data constructor `State'

Stack.hs:9:10: Not in scope: data constructor `State'
Run Code Online (Sandbox Code Playgroud)

这对我来说没有意义,因为据我所知,"State"实际上是一个数据构造函数,定义为

newtype State s a = State { runState :: s -> (a,s) }
Run Code Online (Sandbox Code Playgroud)

指南是"错误的",如果是,我该如何解决?

Vit*_*tus 18

正如我在评论中提到的,你应该使用state而不是State.


问题是它State不是独立的数据类型(或者更确切地说newtype),但它是StateT应用于Identitymonad 的变换器.实际上,它被定义为

type State s = StateT s Indentity
Run Code Online (Sandbox Code Playgroud)

因为它只是type同义词,所以它不能有State构造函数.这就是Control.Monad.State使用的原因state.