#lang racket (require "chez-init.rkt") (require racket/trace) (define fac (lambda (n) (if (zero? n) 1 (* n (fac (- n 1)))))) ;;; Add a continuation parameter and apply it to the body: (define fac (lambda (n k) (apply-cont k (if (zero? n) 1 (* n (fac (- n 1))))))) ;;; Drive the continuation in. (zero? n) is simple: (define fac (lambda (n k) (if (zero? n) (apply-cont k 1) (apply-cont k (* n (fac (- n 1))))))) ;;; Use Capp to move the recursive call to fac up: (define fac (lambda (n k) (if (zero? n) (apply-cont k 1) (fac (- n 1) ... ;;; Encapsulate the continuation k in a continuation that ;;; tells you to multiply two values: (define fac (lambda (n k) (if (zero? n) (apply-cont k 1) (fac (- n 1) (multiplication-cont n k))))) (define-datatype continuation continuation? (halt-cont) (multiplication-cont (n number?) (next-cont continuation?))) (define apply-cont (lambda (cont val) (cases continuation cont [halt-cont () val] [multiplication-cont (n next-cont) (apply-cont next-cont (* val n))])))