In The Scheme Programming Language by Kent Dybvig (4th edition) section 3.4, he describes very clearly what continuation passing style is. For the why he gives two reasons:
- pass more than one result to its continuation, because the procedure that implements the continuation can take any number of arguments.
- CPS also allows a procedure to take separate continuations …, which may accept different numbers of arguments.
Since the first reason can also be done using the values procedure and the second using case-lambda, I’m not clear the advantages of using continuation passing style. Could someone show me some examples of where continuation passing style is appropriate, where it makes the code better, clearer, etc.?
Dybvig uses the explicit continuations in this section to motivate having
call/ccas part of the language. The main point is made near the end of the section when he mentions that writing code without it requires a global tranformation of all code that is used, including functions that you call. So in Scheme you usually build your own construct using macros, and continuations are one of these useful constructs — but you cannot implement them via macros since they implement only local transformations.But using a CPS style directly can still be useful: for example, as he mentions, you could write a function that has more than one continuation, possibly with different arrities — like a parsing function that receives a single-input function to send a parses value to and a nullary failure function to call when parsing fail (and this function might abort with an error or backtrack and try using other parsing rules). Another possible use is when you want to control exactly what goes into the continuation rather than letting
call/ccgrab the full context.There also the obvious case of writing code in a language that has no first-class continuation, making CPSed code your only choice. An example of that would be lots of node.js programs that use IO and pretty much force you to write code in explicit CPS.