Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Capturing a continuation when traversing a list


; Just the square-list functions - plain and simple: (define (square-list lst) (cond ((null? lst) '()) (else (cons (* (car lst) (car lst)) (square-list (cdr lst)))))) ; The square-list function which caputures the desired continuation: (define (square-list lst) (letrec ((square-list-help (lambda (lst c) (cond ((null? lst) '()) (else (call/cc (lambda (e) (cons (if (= c 3) e (* (car lst) (car lst))) (square-list-help (cdr lst) (+ c 1)))))))))) (square-list-help lst 1))) (define xxx (square-list (list 1 2 3 4 5 6))) xxx ; (1 4 #<continuation> 16 25 36) ((caddr xxx) '()) ; This REDEFINES xxx (!!!), which is extremely weird and tricky to deal with xxx ; (1 4) ((caddr xxx) '(1 2 3)) ; Gives an error, because there is no third element in xxx now. ; Third attempt - a variant that assigns the continuation: (define remember-continuation #f) (define (square-list lst) (letrec ((square-list-help (lambda (lst c) (cond ((null? lst) '()) (else (call/cc (lambda (e) (cons (if (= c 3) (begin (set! remember-continuation e) e) (* (car lst) (car lst))) (square-list-help (cdr lst) (+ c 1)))))))))) (square-list-help lst 1))) (square-list (list 1 2 3 4 5 6)) remember-continuation (remember-continuation '()) (remember-continuation '(10 11 12))