Question

Here is my code. As I call continuation twice, I expect "world" be displayed twice. But it output only once. What am I missing?

(define call-with-current-continuation call/cc)
(define (repeat arg)
  (lambda (cc)
    (cc arg)
    (cc arg)))

(display (call/cc (repeat "world")))
Était-ce utile?

La solution

The short version: the continuation you're capturing is bigger than you think it is. When scheme is evaluating the "call/cc", the continuation is "display this result and then exit the program". So, the first call to the continuation inside the body of the (lambda (cc) (cc arg) (cc arg)) will print the value ... and then exit the program.

To get the behavior you want, you probably want a delimited continuation, that captures only the portion of the continuation out to the top level. Different Scheme implementations differ in the availability of delimited continuations (though you can implement delimited continuations in terms of full continuations, at the expense of efficiency).

Racket, for instance, has a "call with composable continuation" that slices off only the portion of the continuation that reaches out to the nearest prompt... and there's an implicit prompt around each top-level expression. So this program:

#lang racket

(define (repeat arg)
  (lambda (cc)
    (cc arg)
    (cc arg)))

(display (call-with-composable-continuation (repeat "world")))

prints "world" twice, as you'd hoped.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top