了解 Haskell 访问器函数
我正在阅读 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”,我可以推断出访问器已经被柯里化到“s”。
所以问题是;如何读取类型定义,以便我可以了解如何在这种情况下调用访问器函数,以及如果可能的话如何读取访问器函数本身。
I'm reading up on Monad tutorials, and the one I'm working on now is http://www.muitovar.com/monad/moncow.xhtml , but I ran on a problem with the state Monad, or to be more precise the runState accessor function.
The type is defined as
newtype State s a = State { runState :: (s -> (a,s)) }
and it's called e.g.
runState (chncasewst3 'e' 'd' 'f') False
I don't know how to read the definition for getting to the second line, especially because of the "State s a" part. If it where "State a s", I could deduce that the accessor has been curried 'as far' as the 's'.
So the question is; how to read the type definition so that I could see how to call the accessor function in this situation, and if possible how to read accessor functions per se.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将数据类型定义为像
一样读取它时
自动定义两个辅助函数
:当您将
getA
应用于T
的值时,结果的类型为一个。
现在,您的
State
类型仅包含一个元素,该类型是一个函数 (:: s -> (a, s)
)。runState
将State s a
类型的值转换为该类型的函数。每次将
runState
应用于State s a
类型的值时,结果都是一个s ->; 类型的函数。 (a,s)
。该函数的第一个参数是状态变量(s
类型)的初始值。在教程示例中,
chncasewst3 'e' 'd' 'f'
的类型为State Bool String
。runState (chncasewst3 'e' 'd' 'f')
的类型为Bool ->; (字符串,布尔值)
。runState (chncasewst3 'e' 'd' 'f') False
的类型为(String, Bool)
。进一步阅读:
When you have a data type defined as
read it like
with two helper functions defined automatically:
When you apply
getA
to the value ofT
, the result is of typea
.Now your
State
type consists of only one element, which type is a function (:: s -> (a, s)
).runState
converts a value of typeState s a
to a function of this type.Every time you apply
runState
to the value of typeState s a
, the result is a function of types -> (a,s)
. And the first argument of this function is an initial value of the state variable (of types
).In the tutorial example,
chncasewst3 'e' 'd' 'f'
has typeState Bool String
.runState (chncasewst3 'e' 'd' 'f')
has typeBool -> (String, Bool)
.runState (chncasewst3 'e' 'd' 'f') False
has type(String, Bool)
.Further reading: