[racket] Continuations & side effects
Part of the problem is that you are running your program within a module.
Unless a variable x is explicitly designated as assignable via (set! x ...),
the execution of a module makes the variable immutable. You can see how it
all gets expanded with the macro stepper (disable hiding):
(module anonymous-module racket
(#%module-begin
(define-values (saved) '*dummy-value*)
(define-values (next-year) (#%app + (quote 1) (#%app call/cc (lambda (g) (set! saved g) (quote 1997)))))
(#%app call-with-values (lambda () (#%app saved (quote 2012))) print-values)))
If you run it in the REPL (dr or r), you get the kind of result you imagine:
Welcome to DrRacket, version 5.3.1.12--2013-01-05(12d670b5/d) [3m].
Language: racket.
> (define saved '*dummy-value*)
> (define next-year (+ 1 (call/cc (lambda (g) (set! saved g) 1997))))
> (saved 2012)
> next-year
2013
In the REPL a define is a set! and Racket treats it that way.
Some other remarks:
1. Racket is a language in the Lisp and Scheme tradition. As such Racket has the freedom to assign its own semantics. Not interpreting define as set! enables optimizations. Also see Chez's treatment of letrec or 2.
#lang scheme is a left-over from eons ago. Use #lang racket.
2. Even in R6RS -- the current 'standard' -- you could argue that a nest of defines should have the same semantics as a letrec and in a letrec the RHS may not return more than once. Implementations may raise an error.
3. Matthew has said in this context "the top-level is hopelessly m'ed up" or something like that. And he's right.
On Jan 6, 2013, at 4:55 PM, Jean-Michel HUFFLEN wrote:
> Hello, Racket users!
>
> Here is an example I difficultly understand:
>
> #lang scheme
> (define saved '*dummy-value*)
> (define next-year (+ 1 (call/cc (lambda (g) (set! saved g) 1997))))
> (saved 2012)
>
> In some other interpreters, it is OK. But Racket's answer is:
>
> define-values: cannot re-define a constant: next-year
>
> I can understand that variables cannot be set by means of continuations in Racket. But if I change it into:
>
> #lang scheme
> (define saved '*dummy-value*)
> (define next-year 1000)
> (set! next-year (+ 1 (call/cc (lambda (g) (set! saved g) 1997))))
> (saved 2012)
>
> there is no error, and "next-year" evaluates to 2013, as expected.
>
> Why such a difference, please?
>
> Yours faithfully,
>
> J.-M. H.
>
>
> ----------------------------------------------------------------
> This message was sent using IMP, the Internet Messaging Program.
>
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users