Exchange symbols

Started by cormullion, September 25, 2006, 04:46:26 AM

Previous topic - Next topic

cormullion

is there a way of swapping two symbols' values?



(set 'x 1 'y 2)

(? x y)

; x is 2, y is 1


without having to do this:



(set 't x 'x y 'y t)

Fanda

#1
I haven't tested speed, but this works:


> (set 'x 1 'y 2)
2
> (map set '(x y) (list y x))
(2 1)
> x
2
> y
1


You can also put it in a macro:
> (define-macro (exchange) (map set (args) (map eval (rotate (args) -1))))
(lambda-macro () (map set (args) (map eval (rotate (args) -1))))

> (set 'a 1 'b 2 'c 3 'd 4)
4
> (exchange a b c d)
(2 3 4 1)
> a
2
> b
3
> c
4
> d
1


Fanda

cormullion

#2
Nice solutions, thanks Fanda!



I assume there's no parallel assignments in newLISP 'out of the box' then?

cormullion

#3
You can do this:



(set 'x 1 'y 2)
; x is 1, y is 2

(swap  x y)
; x is 2, y is 1


as of 8.9.13.



It pays to read the release notes!



Thanks Lutz - I like the way you grant my wishes...!