How can I exchange two variables in LISP without using a third variable?
5 Answers
Also:
(let ((a b) (b a)) ...)
2 Comments
dmitry_vk
That does not change the variables' values, it only creates new lexical bindings.
Michael H.
@dmitry-vk: That's often all you need. It depends on what you're doing, of course.
Another alternative, "parallel setf":
(psetf a b b a)
1 Comment
Bill Evans at Mariposa
A difference between
rotatef and psetf is that if a and b are really more complicated forms, then psetf will evaluate any subforms twice, but rotatef will evaluate them only once, which is what one would normally want.Rather gruesome method and it works only for numerical values, but it's more general and not syntax dependent:
a = a^b
b = a^b
a = a^b
Assuming that a and b were assigned before, the ^ means logical exclusive alternative.
1 Comment
peawormsworth
Fascinating, the two binary numbers really pass through each other without additional space requirements.