#lang racket (require "chez-init.rkt") (require racket/trace) (define length (lambda (ls) (cond [(null? ls) 0] [else (+ 1 (length (cdr ls)))]))) ;;; Add a continuation parameter and apply it to the body: (define length-cps (lambda (ls k) (apply-cont k (cond [(null? ls) 0] [else (+ 1 (length (cdr ls)))])))) ;;; Drive the continuation in. (null? ls) and else are simple: (define length-cps (lambda (ls k) (cond [(null? ls) (apply-cont k 0)] [else (apply-cont k (+ 1 (length (cdr ls))))]))) ;;; Use Capp to move the recursive call to length up: (define length-cps (lambda (ls k) (cond [(null? ls) (apply-cont k 0)] [else (length-cps (cdr ls) ... ;;; Encapsulate the continuation k in a continuation that ;;; tells you to add two values: (define length-cps (lambda (ls k) (cond [(null? ls) (apply-cont k 0)] [else (length-cps (cdr ls) (add-cont 1 k))]))) (define-datatype continuation continuation? (halt-cont) (add-cont (n number?) (next-cont continuation?))) (define apply-cont (lambda (cont val) (cases continuation cont [halt-cont () val] [add-cont (n next-cont) (apply-cont next-cont (+ val n))])))