scala delimited continuation and callcc

本文通过一个具体的 Scala 实现的 Continuation 捕获和调用示例,展示了 callcc 的工作原理及其在 Delimited Continuation 中的应用。该示例包括如何捕获 Continuation、如何调用它们以及 callcc 的具体效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想不出一个 callcc 实际应用的例子 , 搞了个示例性的 . 目的是 :

1.    示范怎样扑捉 continuation

2.    示范怎样调用 continuation

3.    示范 callcc 的效果

4.    这是个 Delimited Continuation 的例子

 

package com.bellcard.continuations

object ContTrial {

  case class M[+A](in: (A=> Any )=> Any ) {

        def apply(f:A=> Any ) = in(f)

        def map[B](f: A => B):M[B]        = bind( this , {x: A => unit(f(x))} )

        def flatMap[B](f: A => M[B]):M[B] = bind( this , f)

  }

  def bind[A,B](m:M[A], f:A=>M[B]):M[B] = 

      M(k => m.in (x => f(x).in(k)))

  def unit[A](x:A):M[A] = M( {k:(A=> Any ) => k(x)} )

  def callcc[A](e:(A=>M[A])=>M[A]):M[A] =  

      M(k => e(a => M(ignored => k(a))).in(k))

     

  def main(args : Array [String]) : Unit = {

      var okcc: Int =>M[ Int ] = null

      var errcc: Int =>M[ Int ] = null

      var speccc: Int =>M[ Int ] = null

      val cc = callcc[ Int ](ok=>

                  callcc[ Int ](specific=>

                  callcc[ Int ](err=>{

                      okcc = ok

                      errcc= err

                      speccc= specific

                      println( "in callcc" )

                      unit[ Int ](1)

                  }) flatMap {x=>{println( "err cc" );unit(x)}}

                  ) flatMap { x=>{println( "specific cc" ); unit(x)}}

               ) flatMap{x=>{println( "ok cc" );unit(x)}}

      cc(println)

      println( "ooooookkkkkkkccccccccc" )

      okcc(10)(println)

      println( "sssspppppeecciifffiiiicccccc" )

      speccc(40)(println)  

      println( "eeeeerrrrrrccccccccc" )

      errcc(30)(println)

  }

}

 

输出 :

in callcc

err cc

specific cc

ok cc

1

ooooookkkkkkkccccccccc

ok cc

10

sssspppppeecciifffiiiicccccc

specific cc

ok cc

40

eeeeerrrrrrccccccccc

err cc

specific cc

ok cc

30

 

在最内层的 callcc , okcc = ok, errcc=err, speccc=specific 来扑捉 continuation.

callcc 包含 callcc continuation(是不是叫inside-out?). 例如 , 调用 errcc(30) 会调用 okcc speccc. 而调用 okcc 则不会调用 errcc speccc, 因为它是最外层的

Continuation 是有边界的 (delimited), 在最外层的 callcc 是其边界

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值