【发布时间】:2012-03-14 08:08:04
【问题描述】:
我正在阅读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) }
指南是否“错误”,如果是,我该如何解决?
【问题讨论】:
-
Control.Monad.State不导出State构造函数,使用state(小写s)。 -
@Vitus 不错,我不知道that function 被导出了。我认为您应该将其写为答案而不是评论。
-
@Vitus:那很奇怪,因为他的代码实际上可以在我的 Windows 上的 GHCI 6.12.3 上编译并运行良好。
-
@Riccardo
State已弃用,取而代之的是StateT。由于Statemonad 可以在Identitymonad 上定义为StateT,所以它现在是一个类型同义词并且没有State数据构造函数。 -
好吧,那只是因为learnyouahaskell老了? :)