schemeracketchez-scheme

set of x and x does not work in let in Scheme


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!


Solution

  • 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)