It’s common for explanations of continuations to say that a continuation represents the “rest of the program” (or similar phrasing). But there’s plainly a boundary at which the continuation stops collecting these remaining computation steps. What is that boundary? The top level of the program? Or something else?
These explanations tend to start with a toy example like this.
(+ 1 (call/cc
(lambda (cc)
(cc 2))))
This evaluates to 3 because (cc 2) means “put 2 in the hole in the expression carved out by the call/cc form.” The expression becomes (+ 1 2), aka 3.
Now consider this example:
(define lc #f)
(+ 1 (call/cc
(lambda (cc)
(set! lc cc)
(cc 2))))
(displayln "done")
(lc 42)
Here, we stash the continuation cc in the variable lc. After the expression is evaluated, we display done and use the continuation again as (lc 42).
What do we get?
3
done
43
But … why? If a continuation is the “rest of the program”, why doesn’t the continuation capture everything that happens after call/cc, which includes the subsequent calls to displayln and lc? Under this interpretation, the continuation would create an infinite loop.
Plainly, that’s not what happens. Rather, it appears that the continuation is capturing the rest of the program until it reaches a subsequent expression, which it ignores (along with any others).
But now consider this example:
(define lc #f)
(define (f)
(displayln (+ 1 (call/cc
(lambda (cc)
(set! lc cc)
(cc 2)))))
(displayln "done"))
(f)
(displayln "outer")
(lc 42)
The result in this case is:
3
done
outer
43
done
Meaning, the continuation does capture the (displayln "done") in f, though it still does not capture the (displayln "outer") and (lc 42) following the invocation of f.
One final example — we move everything into a new function g:
(define lc #f)
(define (g)
(define (f)
(displayln (+ 1 (call/cc
(lambda (cc)
(set! lc cc)
(cc 2)))))
(displayln "done"))
(f)
(displayln "outer")
(lc 42))
(g)
This time, we get the infinite loop predicted in the earlier example:
3
done
outer
43
done
outer
43
···
So the original intuition was not completely off-base. Is this just another instance of the top level being hopeless? Or is there a more succinct explanation of how far a continuation reaches?