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!
My end goal is to switch their values only with commands, not with temporary variables
It looks like racket supports set!-values, so you can swap your variables without using any explicit temporary variables like so:
(define x 1)
(define y 2)
(set!-values (x y) (values y x))
;;; x is now 2 and y is 1
(It's even the example in the linked documentation)
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.