On this page:
7.1 Not CPS
7.2 CPS
7.2

7 Continuation-passing style

(Not really working with the Racket file in this part. Can play with stuff in the Racket REPL.)

Say we want a function that adds two to its argument.

7.1 Not CPS

A reasonably normal way to go about things could be:
(define (add2 x)
  (+ x 2))
If we wanna apply it to the number three and display the result, then we can apply it to 3 and display:

(display (add2 3))

Chances are the number 5 will be displayed.

7.2 CPS

A less normal way to go about things could be: Instead of add2-function taking just one argument, it could take two arguments and the second argument could be a “continuation”-argument. And instead add2 returning the result of the addition, it could apply its “continuation” to the result.
(define (add2 x continue)
  (continue (+ x 2)))
Now, if we wanna display the result, we do not apply display to the result. Instead we pass in display as add2’s continue-argument.

(add2 3 display)

If we don’t exactly have the exact functions we want at hand, we can make them with lambdas.

(add2 3
      (λ (result)
        (add2 result
              (λ (final-result)
                (printf "it's ~a" final-result)))))

So that’s weird. Anyway we’re passing continuations. That style of programming is called continuation-passing style (CPS).

Next is Refactoring to CPS.