7

How can I exchange two variables in LISP without using a third variable?

5 Answers 5

25
(rotatef a b)
Sign up to request clarification or add additional context in comments.

Comments

1

Also:

(let ((a b) (b a)) ...)

2 Comments

That does not change the variables' values, it only creates new lexical bindings.
@dmitry-vk: That's often all you need. It depends on what you're doing, of course.
1

Another alternative, "parallel setf":

(psetf a b b a)

1 Comment

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.
0

Yet another approach:

(setf (values a b) (values b a))

Comments

-3

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

Fascinating, the two binary numbers really pass through each other without additional space requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.