What's a Closure?

  1. What's a Closure?
  2. Variables and Values
  3. Defining Functions
  4. Side Effects
  5. Functions are Values
  6. Returning Functions
  7. Function Scope
  8. Nested Functions
  9. Stateful Closures
  10. Private Data
  11. Asynchronous Callbacks
  12. Continuation Passing

Continuation Passing

A continuation is a callback function that represents what to do next. You call a continuation to keep going, rather than returning from a function. If you totally convert your program to never use return and to only call continuations, you have transformed your program into continuation-passing style. Here is a function that adds one to a number, in regular and in continuation-passing style.

In continuation-passing style, every function gets an extra argument ret that is called instead of returning. Nothing ever returns! Pretty crazy.

We're not limited to just one continuation. Suppose every function gets a success and failure continuation. Here's what addOne might look like.

Here is an example of a sequencing operation seqC. The function seqC takes two functions fC and gC, along with continuations success and failure. The functions fC and gC themselves just take continuations success and failure, they don't handle any data. The seqC operator runs fC and if it succeeds keeps going. If fC fails, then it runs gC and keeps going.

That code can actually be simplified. For example, we can just say success instead of f_success. Here's the simplified version.

Define a function named bothC similar to seqC that takes functions fC and gC and continuations success and failure. The functions fC and gC both just take success and failure continuations. Your function bothC should call both fC and gC no matter what, but only call success if both succeeded, and failure otherwise. Don't forget, your function will never return!


about news main