我正在阅读 Learn You a Haskell's guide on the state monad ,但由于堆栈示例无法编译,因此我无法理解它。在指南中,他使用了以下代码:
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)
虽然我理解它应该做什么,但它不会编译。我不知道为什么。错误信息是:
Stack.hs:6:7: Not in scope: data constructor `State'
Stack.hs:9:10: Not in scope: data constructor `State'
这对我来说毫无意义,因为据我所知,“状态”实际上是一个数据构造函数,定义为
newtype State s a = State { runState :: s -> (a,s) }
指南是否“错误”,如果是,我该如何解决?
最佳答案
正如我在评论中提到的,你应该使用 state
而不是 State
.
问题是 State
不是独立的数据类型(或者更确切地说 newtype
),但它是 StateT
变压器应用于Identity
单子(monad)。实际上,它被定义为
type State s = StateT s Indentity
因为它只是
type
同义词,不能有State
构造函数。这就是为什么Control.Monad.State
使用 state
.
关于haskell - 状态单子(monad)和 learnyouahaskell.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9697980/