延续单声道到底如何工作 [英] How does continuation monad really work
问题描述
我了解读者",也许"或州"单子的工作方式,但在"Continuations"单子下艰难度日.像下面这样的例子,让我震惊
I understand how Reader or Maybe or State monads work, but havig hard times with Continuations monad. Examples like below, blow my head
type ContinuationMonad() =
member this.Bind (m, f) = fun c -> m (fun a -> f a c)
member this.Return x = fun k -> k x
我认为我的问题是我无法获得连续的单子类型(例如Cont<'T>)以及如何解开并回卷.任何有用的示例或链接都将受到高度赞赏.
I think that my problem is that I cannot get what is a monadic type for Continuation (like Cont<'T>) and how i can unwrap it and wrap back. Any helpful examples or links are highly appreciated.
推荐答案
在其他地方我不会重复所说的-注释中提到的帖子提供了有关延续单子的很多细节.但是,可能有帮助的一件事是使用 Cont<'T>
:
I will not repeat what has been said elsewhere - the post mentioned in the comments gives a lot of details about the continuation monad. But one thing that might help is to rewrite your code snippet with an explicit definition for Cont<'T>
:
type Cont<'T> =
Cont of (('T -> unit) -> unit)
类型 Cont<'T>
表示计算.您可以通过为其赋予功能'T->来启动.单元
获取结果并对其进行处理(例如,打印结果).当您启动它时,它将返回 unit
,并且(在某个时候)将产生一个值'T
并调用您提供的 continuation .
The type Cont<'T>
represents a computation. You can start it by giving it a function 'T -> unit
that takes the result and does something with it (say, prints it). When you start it, it returns unit
and it will (at some point) produce a value 'T
and call the continuation you provided.
使用此更明确的定义,可以将构建器定义为:
With this more explicit definition, the builder can be defined as:
type ContinuationMonad() =
member this.Bind (ma, f) =
Cont(fun k ->
let (Cont ca) = ma
ca (fun a ->
let (Cont cb) = f a
cb k))
member this.Return x =
Cont(fun k -> k x)
-
Return
成员创建一个计算,当给定延续性k
时,该计算立即使用值x
调用该延续性我们回来了.The
Return
member creates a computation that, when given a continuationk
, calls this continuation immediately with the valuex
that we returned.Bind 成员返回一个新的计算,当给定连续性
k
时,该计算将开始由m
指定的计算;当此计算产生值a
时,它将调用函数f
,然后 then 调用由f
返回的计算,其中原始延续k
(这是最终应以最终结果调用的最终"延续).The
Bind
member returns a new computation that, when given a continuationk
, starts the computation specified bym
; when this computation produces a valuea
, it calls the functionf
and then calls the computation returned byf
with the original continuationk
(which is the "final" continuation that should eventually be called with the final result).这篇关于延续单声道到底如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!