How can I exchange two variables in LISP without using a third variable?
LISP variable exchange
Asked Answered
Also:
(let ((a b) (b a)) ...)
That does not change the variables' values, it only creates new lexical bindings. –
Nonunionism
@dmitry-vk: That's often all you need. It depends on what you're doing, of course. –
Shirring
Another alternative, "parallel setf":
(psetf a b b a)
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. –
Barroom Yet another approach:
(setf (values a b) (values b a))
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.
Fascinating, the two binary numbers really pass through each other without additional space requirements. –
Pittman
© 2022 - 2024 — McMap. All rights reserved.