[英]Creating a `State [Int] Int`
Reading through Learn You a Haskell , I'm trying to construct a Stack [Int] Int
: 通过阅读《 学习Haskell》 ,我正在尝试构建
Stack [Int] Int
:
ghci>import Control.Monad.State
ghci> let stack = state ([1,2,3]) (1) :: State [Int] Int
<interactive>:58:20:
Couldn't match expected type `s0 -> (State [Int] Int, s0)'
with actual type `[t0]'
In the first argument of `state', namely `([1, 2, 3])'
In the expression: state ([1, 2, 3]) (1) :: State [Int] Int
In an equation for `stack':
stack = state ([1, 2, 3]) (1) :: State [Int] Int
How can I create a Stack [Int] Int
? 如何创建
Stack [Int] Int
?
It depends on what you're trying to do. 这取决于您要执行的操作。
State sa
is essentially a newtype
for a certain kind of function type (specifically s -> (a, s)
), so it doesn't really make sense to make a State
value from just a list. State sa
本质上是一个newtype
为某一种功能型的(特别是s -> (a, s)
所以它并没有真正意义做一个State
只从一个列表值。 The simplified (internal) definition of State
looks something like 的简化(内部)定义
State
看起来像
newtype State s a = State { runState :: s -> (a, s) }
Though you won't use the State
constructor directly, it does illustrate the fact that a State sa
value consists of a function. 尽管您不会直接使用
State
构造函数,但它确实说明了State sa
值包含一个函数这一事实。
You need a function that updates the state in some way (which could be considered a " State
action"), then you can use runState :: State sa -> s -> (a, s)
to execute the provided State
action, given a certain initial state (the s
argument). 您需要一个以某种方式更新状态的函数(可以将其视为“
State
动作”),然后可以使用runState :: State sa -> s -> (a, s)
执行给定的State
动作。某个初始状态( s
参数)。
It looks like you want to use [1, 2, 3]
as your initial state, but you do also need to provide that update function (which is what you use to construct the State sa
value itself). 看起来您想使用
[1, 2, 3]
作为初始状态,但是您也确实需要提供该更新功能(用于构造State sa
值本身的功能)。
In the Learn You a Haskell example, the Stack
type synonym represents the actual stack data while State Stack ...
represents a stateful action on the Stack
data. 在“学习Haskell”示例中,
Stack
类型同义词表示实际堆栈数据,而State Stack ...
表示对 Stack
数据的有状态操作。 For instance, an action of type State Stack Int
uses a Stack
value as its state and results in an Int
when it is executed. 例如,类型为
State Stack Int
将Stack
值用作其状态,并在执行时产生一个Int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.