Different outputs about saved continuations in DrRacket's definitions window and interactions window

Viewed 55

I'm new to Racket and I'm trying to use call/cc. When I put the following code in the definitions window of DrRacket, run it, and type (saved-k 0) in the interactions window, I get two of 3 printed.

#lang racket ; the definitions window

(define saved-k #f)

(define (f)
  (+ 1
     (call/cc (λ (k) (set! saved-k k) 0))))

(+ 1 (+ 1 (f)))
; the interactions window
3
> (saved-k 0)
3
3

My understanding is that the saved continuation should be (+ 1 (+ 1 (+ 1 ?))) where ? is the hole. Why are there two results printed?

When I try all of those things in the interactions window, everything looks normal.

; the interactions window
> (define saved-k #f)
> (define (f)
    (+ 1
       (call/cc (λ (k) (set! saved-k k) 0))))
> (+ 1 (+ 1 (f)))
3
> (saved-k 0)
3
1 Answers

Racket prints values at the top level. For example, running

#lang racket
1
2

will print 1 and 2.

How is this done? Well, when the program is run, it expands the code to something like:

(module test racket
  (#%module-begin
   (#%app call-with-values (lambda () '1) print-values)
   (#%app call-with-values (lambda () '2) print-values)))

where print-values is responsible for the printing.

What happened in your program is that when the continuation is captured, it includes the print-values frame. That's why when you invoke the continuation, you see the double printing. One from print-values. Another from the evaluation result.

But when you try them all in the interactive window, there's no print-values, so there's no double printing.

Related