What’s in a Continuation (2016)
It took a long time to grok continuations. There's an easy way to explain what they are:<p>Imagine running a program in a VM. You know how you can take a snapshot and then restore to it later? That snapshot is equivalent to a continuation.<p>Another way of phrasing it is, it's your program frozen in time. You can snapshot your program and restore to that point later.<p>To put it technically, step through each call stack frame, serialize all the local variables, and you have yourself a continuation. To invoke it, call those functions in order and set the local variables to those values, then set the program counter to wherever it was. (You don't literally do this, but maybe that makes it easier to understand what's going on with it.)<p>The confusion: What about a database connection? Or a network connection of any kind? An open file handle? Etc. The answer is that those things can't be saved in a continuation.<p>The way that this works in Scheme is that there's a special primitive called "dynamic wind". It takes three callback functions: "before", "during", and "after". It invokes those callback functions in order. If execution leaves "during" for any reason whatsoever, then "after" is invoked.<p>Here's the kicker: If execution <i>goes back into "during"</i>, then "before" is invoked. I.e. if you save a continuation inside "during," then "before" is the place that you'd put the code to re-initiate a database connection or re-open a file handle. Or fail.<p>And of course, no discussion of continuations would be complete without the argument for why call/cc is generally an anti-pattern: <a href="http://okmij.org/ftp/continuations/against-callcc.html" rel="nofollow">http://okmij.org/ftp/continuations/against-callcc.html</a><p>Yet "On Lisp" presents several interesting ways to use them, and they are extremely powerful. One particular use is that you can implement cut, fail, and mark for non-deterministic backtracking. If you've used emacs lisp and you've ever written an edebug specification for how to debug a macro (<a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Specification-List.html#Specification-List" rel="nofollow">https://www.gnu.org/software/emacs/manual/html_node/elisp/Sp...</a>), some of the more complex features require backtracking: <a href="https://github.com/emacs-mirror/emacs/blob/0648edf3e05e224ee8410ab244df7364f919dc58/lisp/emacs-lisp/cl-macs.el#L2578-L2595" rel="nofollow">https://github.com/emacs-mirror/emacs/blob/0648edf3e05e224ee...</a><p>That's an area where continuations really shine, because the implementation can be just a few dozen lines compared to hundreds.<p>(elisp doesn't actually use continuations -- this is just an example of the territory they're useful in.)