Usually, I avoid using mutations since you rarely need them.
However, I need them and I am trying to understand better somethings. There is a specific behavior that intrigues me and I would like to ask for your help to understand it better.
If I type on the REPL the change bellow everything works:
> (define x 1)
> (set! x (+ x 1))
> x
2
If I put the assignment and the mutation on the definition window it also works:
(define y 1)
y
(set! y (+ y 1))
y
After running the file, I can see on the REPL the following correct result:
1
2
>
However, if I put the definition of variable x
on the definition windows and if I try to set! it to a new value on the REPL I get an error:
; Definition Window
(define y 1)
;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;
; REPL
> (set! y (+ y 1))
. . y: cannot modify a constant
Why does that happen? Shouldn't interactive programming be used especially for situations like this?
Thanks in advance.
According to Matthias Felleisen, one of the main responsible for the development of Racket so far:
The DrRacket REPL allows set!s on those variables that are assignable in the module and no others. That's by design. Roughly speaking, think of the Definitions window as a module and the REPL a way to perform computations as if we were a client of the module that can also use all of its internally defined functions, think super-client. But this super-client view does not enable you to mutate variables that weren't mutable in the first place .. just like a client can't do that either.
This information was presented in Racket's Mail list 7 years ago as pointed out in a comment of my own question in the post above.