我正在阅读 Monad 教程,我现在正在研究的是 http://www.muitovar.com/monad/moncow.xhtml ,但我遇到了状态 Monad 的问题,或者更准确地说是 runState 访问器函数。
类型定义为
newtype State s a = State { runState :: (s -> (a,s)) }
它被称为例如
runState (chncasewst3 'e' 'd' 'f') False
我不知道如何阅读第二行的定义,尤其是因为“State s a”部分。如果它在“State a s”的位置,我可以推断出访问器已被“curried”到“s”。
所以问题是;如何阅读类型定义,以便我可以看到在这种情况下如何调用访问器函数,以及如果可能的话如何阅读访问器函数本身。
最佳答案
当您将数据类型定义为
data T a b = MkT { getA :: a, getB :: b }
读起来像
data T a b = MkT a b
自动定义了两个辅助函数:
getA :: (T a b) -> a
getA (MkT x _) = x
getB :: (T a b) -> b
getB (MkT _ y) = y
申请时
getA
为 T
的值,结果的类型为 a
.现在您的
State
type 仅由一个元素组成,该类型是一个函数 (:: s -> (a, s)
)。 runState
转换 State s a
类型的值到这种类型的函数。ghci> :t runState
runState :: State s a -> s -> (a, s)
每次申请
runState
到类型 State s a
的值, 结果是 s -> (a,s)
类型的函数.该函数的第一个参数是状态变量的初始值(类型为 s
)。在教程示例中,
chncasewst3 'e' 'd' 'f'
有类型 State Bool String
. runState (chncasewst3 'e' 'd' 'f')
有类型 Bool -> (String, Bool)
. runState (chncasewst3 'e' 'd' 'f') False
有类型 (String, Bool)
. 进一步阅读:
关于haskell - 了解 Haskell 访问器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240947/