(define (non-number-value-error x)
(display "Value error: ")
(display x)
(display " is not number.")
(newline)
'error)
(define (kproduct ls k k-value-error)
(let ((break k))
(let loop ((ls ls) (k k))
(cond
((null? ls) (k 1))
((not (number? (car ls))) (k-value-error (car ls)))
((zero? (car ls)) (break 0))
(else (loop (cdr ls) (lambda (x) (k (* (car ls) x)))))))))
;;; valid
(kproduct '(2 4 7)
(lambda (x) (k+ x 100 return))
non-number-value-error)
;Value: 156
;;; invalid
(kproduct '(2 4 7 hoge)
(lambda (x) (k+ x 100 return))
non-number-value-error)
Value error: hoge is not number.
;Value: error
从这个例子中可以看出,CPS风格的程序类似尾递归,需要的中间状态都融合在不停构建的新函数中。比如下例就不是尾递归,因为它除了正常该有的error消息外,还有解释器打出的异常信息:
(define (fact n)
(if (= n 1)
1
(if (< n 3)
(non-number-value-error n)
(* n (fact (- n 1))))))
(fact 6)
继续阅读,发现下面总结了一下Continuation:
You may grasp what is continuation by the above explanation.Continuation
exists whole computional processes, and
it can be treated explicitly by a functional programming language and CPS.
In addition, examples above show that it is a chain of closure.
浙公网安备 33010602011771号