Prev Up Next
Escaping continuations are the simplest use of
call/cc and are very useful for programming
procedure or loop exits. Consider a procedure
list-product that takes a list of numbers and
multiplies them. A straightforward recursive
definition for list-product is:
(define list-product
(lambda (s)
(let recur ((s s))
(if (null? s) 1
(* (car s) (recur (cdr s)))))))
There is a problem with this solution. If one of the
elements in the list is 0, and if there are many
elements after 0 in the list, then the answer is a
foregone conclusion. Yet, the code will have us go
through many fruitless recursive calls to recur
before producing the answer. This is where an escape
continuation comes in handy. Using call/cc, we can
rewrite the procedure as:
(define list-product
(lambda (s)
(call/cc
(lambda (exit)
(let recur ((s s))
(if (null? s) 1
(if (= (car s) 0) (exit 0)
(* (car s) (recur (cdr s))))))))))
If a 0 element is encountered, the continuation
exit is called with 0, thereby avoiding
further calls to recur.
Prev Up Next