延续单声道到底如何工作 [英] How does continuation monad really work

查看:61
本文介绍了延续单声道到底如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解读者",也许"或州"单子的工作方式,但在"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 continuation k, calls this continuation immediately with the value x that we returned.

      Bind 成员返回一个新的计算,当给定连续性 k 时,该计算将开始由 m 指定的计算;当此计算产生值 a 时,它将调用函数 f ,然后 then 调用由 f 返回的计算,其中原始延续 k (这是最终应以最终结果调用的最终"延续).

      The Bind member returns a new computation that, when given a continuation k, starts the computation specified by m; when this computation produces a value a, it calls the function f and then calls the computation returned by f with the original continuation k (which is the "final" continuation that should eventually be called with the final result).

      这篇关于延续单声道到底如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆