CSC152 2006S, Class 9: Continuations Admin: * Options for Monday: Lab (no reading) or Continuations and the Web (belated readings) * Disappointed in the lack of responses to the readings. * Questions on the homework? * Notes on Church numerals * Alex and DaveV showed up early. * Dimitar is late again. Overview: * Continuation basics * Applications of continuations * Continuations and the Web /Church Numerals/ * Definition of numbers within the lambda calculus * Definition based on "zero and successor" * Each number is a function * Each number has the form \ s z . (s (s .... (s z))) * Number n has n s's in the rhs /Continuations/ * Functions that represent 'the state of the program' or 'what happens next' > (+ 4 (* 3 (- (+ x x) a))) The continuation for (* ...) is "add 4" or (lambda (x) (+ x 4)) The continuation for (- ...) is multiply by 3 and then add 4, or (lambda (x) (+ 4 (* 3 x))) The continuation for (+ x x) is ... * Every language has an implicit notion of continuations (after all, there is always "the next code to execute" * Scheme makes these continuations first-class objects: You can get them, send them to functions, call them, etc. * When you call a continuation, you replace the current continuation with the called continuation * To get a continuation, use (call-with-current-continuation (lambda (cont) ...)) -- Wrap up the current continuation and pass it to lambda (cont) (call/cc (lambda (cont) ...)) -- Alias for call-with-.... (let/cc k body) -- Pack up the current continuation and call it k, then execute body - Same as (call/cc (lambda (k) body)) * Simplest useful application of continuations: Exceptions * Another useful application: Pausing code * Create two global continuations: * exit - return to the top level * resume - restart the code at the stopped pointa * Graham example: You can pause and restart tree traversal * Another useful application: coroutining Continuations not necessary, but can make the coding easier (once you understand them well) The fun use of continuations: Saving state on the Web * Write an interactive program that is not Web-based * Replace each request for input and change it to * Grab the current continuation * Name and store that continuation for later reuse * Generate a Web page with a form that requests input (and has the continuation name in a hidden field) * When a page is submitted, get the continuation and call the continuation on the other returned values