创建`State [Int] Int`

Kev*_*ith 0 haskell state-monad

通过Learn You a 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
Run Code Online (Sandbox Code Playgroud)

我该如何创建Stack [Int] Int

Dav*_*vid 6

这取决于你想要做什么.State s a本质上是newtype一种特定类型的函数类型(具体而言s -> (a, s)),因此State从列表中创建一个值并没有多大意义.简化(内部)定义State看起来像

newtype State s a = State { runState :: s -> (a, s) }
Run Code Online (Sandbox Code Playgroud)

虽然您不会State直接使用构造函数,但它确实说明了一个State s a值由函数组成的事实.

您需要一个以某种方式更新状态的函数(可以被视为" State操作"),然后您可以使用runState :: State s a -> s -> (a, s)State给定某个初始状态(s参数)的情况下执行提供的操作.

看起来您希望将其[1, 2, 3]用作初始状态,但您还需要提供该更新功能(这是您用来构造State s a值本身的功能).

在了解您一个Haskell例如,Stack类型同义词代表实际的堆栈数据,同时State Stack ...表示有状态的动作Stack数据.例如,类型的操作State Stack Int使用Stack值作为其状态,并在Int执行时生成.