简体   繁体   English

`get`如何在State monad的CPS版本中工作?

[英]How does `get` work in the CPS version of the State monad?

I am trying to understand continuation in general following this tutorial . 我试图在本教程后继续理解延续。

However, I am having difficulties to understand following example in section 2.10: 但是,我很难理解2.10节中的以下示例:

# let get () =
    shift (fun k -> fun state -> k state state) ;;
get : unit => ’a = <fun>

state is of type int I suppose. 我认为stateint类型。 What I don't get is the type of k . 我没有得到的是k的类型。 According to my understanding, k captures all computation comes subsequently after get () , and since we are talking about a state monad, k is reasonable to represent a computation that will be continued by taking an int , hence 根据我的理解, k捕获随后在get ()之后的所有计算,并且因为我们讨论的是状态monad,所以k是合理的,表示将通过取一个int继续的计算,因此

k : int => 'a

but from the code, it doesn't seem to do that and it takes state for a second time, which actually implies: 但是从代码来看,它似乎没有这样做,它第二次需要state ,这实际上意味着:

k : int => int => 'a

but I don't get where the second one is coming from, and in which sense get is of type unit => 'a instead of unit => int => 'a ? 但是我没有得到第二个来自哪里,并且在哪种意义上get是type unit => 'a而不是unit => int => 'a

Compared to the actual state monad implementation, the confusion adds more: 与实际状态monad实现相比,混乱增加了更多:

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

ie state transition is represented as a function from state to a tuple of result and state, which matches my first understanding. 即状态转换表示为从状态到结果和状态元组的函数,这与我的第一个理解相匹配。

Can anyone give a lead? 任何人都可以领先吗?

Secondly, how am I supposed to implement get here using Haskell's Control.Monad.Trans.Cont ? 其次,我怎么来实现get这里使用Haskell的Control.Monad.Trans.Cont I am having problems comforting the type system. 我在安慰类型系统方面遇到了问题。


UPDATE UPDATE

It seems I got the second one: 看来我得到了第二个:

Prelude Control.Monad.Trans.Cont> let get () = shift $ \k -> return $ \i -> k i i

But I still don't get why I need to apply the state twice to the continuation. 但我仍然不明白为什么我需要将状态两次应用于延续。

You apply k on state twice because the first one corresponds to the result of get () (we want get 's effect to be retrieving the current state and returning it as the result) and the second one corresponds to passing the state after the get (which, because get doesn't change the state, is the same as the state before the get ) to the next stateful computation. 你在state上应用k两次,因为第一个对应于get ()的结果(我们希望get的效果是检索当前状态并将其作为结果返回),第二个对应于在get之后传递状态(因为get不会改变状态,与get之前的状态相同)到下一个有状态计算。

In other words, since the state monad is State sa ~ s -> (a, s) , its CPS version is State sra ~ s -> (a -> s -> r) -> r , and so for get : State ss , because a ~ s , the continuation will be a function of type s -> s -> r . 换句话说,由于状态monad是State sa ~ s -> (a, s) ,它的CPS版本是State sra ~ s -> (a -> s -> r) -> r ,所以对于get : State ss ,因为a ~ s ,延续将是s -> s -> r类型s -> s -> r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM