I'm trying to run this line in Scheme:
(let ((x y) (y x)) (set! x x) (set! y y))
where at the start of the program x is defined to be 1 and y is defined to be 2. I want the output to be x=2 and y=1 but I get x=1 and y=2
Appreciate your help!
I'm trying to run this line in Scheme:
(let ((x y) (y x)) (set! x x) (set! y y))
where at the start of the program x is defined to be 1 and y is defined to be 2. I want the output to be x=2 and y=1 but I get x=1 and y=2
Appreciate your help!
In this expression:
(set! x x)
Both x
reference the same variable, the one introduced by the let
binding. Any change you do to x
inside the let
(and here, the actual value is unchanged) is not visible outside the let
, because outside the let
the x
symbol is bound to another variable.
If you rename your temporary variables a
and b
for example:
(let ((a y) (b x)) (set! x a) (set! y b))
You will observe a different behaviour.
It looks like racket supports
set!-values
, so you can swap your variables without using any explicit temporary variables like so:(It's even the example in the linked documentation)