Scheme-CPS
给出斐波那契数列计算函数,普通版和CPS版
#lang SCHEME
(define (fib n)
(if (< n 2) n
(+ (fib (- n 1))
(fib (- n 2)))))
(define (fib-cps n k)
(if (< n 2)
(k n)
(fib-cps (- n 1)
(lambda (fib-n-1)
(fib-cps (- n 2)
(lambda (fib-n-2)
(k (+ fib-n-1 fib-n-2))))))))
(define (k n) n)
命令行调用如下
Welcome to DrRacket, version 6.5 [3m].
Language: SCHEME, with debugging; memory limit: 128 MB.
> display (fib-cps 6 k)
#<procedure:display>
8
>
嗯,再看一下阶乘的例子,毕竟两个是成双出现,呵呵
(define (fact n)
(if (= n 0) 1
(* n (fact (- n 1)))))
k函数的定义同上。