Lecture overview -- Keyboard shortcut: 'u'  Previous page: The catch and throw idea -- Keyboard shortcut: 'p'  Next page: The intuition behind continuations -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home    Lecture 3 - Page 35 : 42
Functional Programming in Scheme
Name binding, Recursion, Iteration, and Continuations
A catch and throw example

We now give a Common Lisp like example of catch and throw.

Exit from a list length function in case it discovers a non-empty tail of the list

(define (list-length lst)
  (catch 'exit
    (letrec ((list-length1
               (lambda (lst) 
                 (cond ((null? lst) 0)
                   ((pair? lst) (+ 1 (list-length1 (cdr lst))))
                   (else (throw 'exit 'improper-list))))))
       (list-length1 lst))))

An example using catch and throw. Please notice that the example is not a proper Scheme program. Catch and throw are not defined in Scheme.

Catch and throw are not available in standard Scheme