摘要:简要介绍了scheme语言中continuation的用法。解释了阴阳谜题程序的运行过程与结果。
Scheme是一种lisp方言,个人比较常用的运行环境是MIT-GNU Scheme。
今天谈一谈Continuation,是scheme的一种特性。一个有趣而神秘的应用是阴阳谜题。它将连续不断的打印出一列字符串。@*@**@***。。。这段小代码充分体现了continuation的魅力。
(define call/cc call-with-current-continuation)
(let* ((yin ( (lambda (foo) (display "@") foo) (call/cc (lambda (bar) bar))))
(yang ( (lambda (foo) (display "*") foo) (call/cc (lambda (bar) bar)))))
(yin yang))
continuation本质就是control context的抽象,能够实现函数式语言里原本没有的跳转结构,类似break, return, goto等等。continuation就是一个单参数的过程,它等待输入一个值,然后继续其余的运算。或者也可以把这个continuation保存在一个变量里,当这个变量被调用时,相当于返回到定义continuation的那个点重新开始计算。
continuation语法结构是:
(前面的代码... call-with-current-continuation (lambda(k) body) ...后面的代码)
这就是一个过程,过程名为call-with-current-continuation(通常可以define为call/cc),ca