“状态"的数据构造函数在哪里? [英] Where is the data constructor for 'State'?
问题描述
在阅读了有关Haskell状态单子的一些教程之后,我想亲自尝试一下.我阅读的教程声称Control.Monad.State提供以下定义:
After reading a couple of tutorials on Haskell state monads I wanted to try them out myself. The tutorials I read claim that the Control.Monad.State provide the following definition:
newtype State s a = State { runState :: s -> (a,s) }
但是,我似乎很难找到State
数据构造函数:
However, I seem to be having trouble find the State
data constructor:
Prelude> import Control.Monad.State
Prelude Control.Monad.State> :t State
<interactive>:1:1:
Not in scope: data constructor `State'
Perhaps you meant `StateT' (imported from Control.Monad.State)
我还尝试了Hoogle搜索State
,但是没有找到任何具有预期类型的数据构造函数.
I also tried a Hoogle search for State
but did not find any data constructors with the expected type.
State
构造函数在哪里?它曾经存在吗?还是我只是在错误的地方看?本质上,我想知道创建状态monad需要做什么.
Where did the State
constructor go? Did it ever exist? Or am I just looking in the wrong place? Essentially I would like to know what I need to do to create a state monad.
推荐答案
它不再存在.不幸的是,这使得网络上许多Haskell资源过时了.
It doesn't exist any more. Unfortunately, this makes many Haskell resources on the web about it outdated.
要创建值,只需使用 state
函数:
To create a value, you can just use the state
function:
state :: (s -> (a, s)) -> State s a
runState
曾经是State
的字段,现在本身只是一个普通函数,但其工作方式与以前相同.
runState
, which used to be a field of State
, is now just a normal function itself, but it works in the same way as before.
State
已根据StateT
monad转换器进行了重写:
State
has been rewritten in terms of the StateT
monad transformer:
type State s = StateT s Identity
StateT
本身具有构造函数StateT
,其功能与旧的State
构造函数非常相似:
StateT
itself has a constructor StateT
that functions very similarly to the old State
constructor:
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
唯一的区别是,还有一个额外的参数m
.这只是一个插槽,您可以在其中添加任何其他monad,然后StateT
可以使用状态处理功能进行扩展.自然地,要恢复State
的旧功能,只需将m
设置为Identity
,这不会做任何事情.
The only difference is that there is an extra parameter m
. This is just a slot where you can add in any other monad, which StateT
then extends with state-handling capabilities. Naturally, to regain the old functionality of State
, you just have to set m
to Identity
, which doesn't do anything.
newtype Identity a = Identity { runIdentity :: a }
这篇关于“状态"的数据构造函数在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!