LISP variable exchange
Asked Answered
S

5

7

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

Selwin answered 9/2, 2009 at 22:10 Comment(0)
T
25
(rotatef a b)
Tantalum answered 10/2, 2009 at 1:28 Comment(0)
S
1

Also:

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

Shirring answered 9/7, 2009 at 0:33 Comment(2)
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
L
1

Another alternative, "parallel setf":

(psetf a b b a)

Lepido answered 8/11, 2012 at 20:38 Comment(1)
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
S
0

Yet another approach:

(setf (values a b) (values b a))
Sequestrate answered 16/1, 2017 at 19:51 Comment(0)
M
-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.

Midpoint answered 28/2, 2014 at 18:28 Comment(1)
Fascinating, the two binary numbers really pass through each other without additional space requirements.Pittman

© 2022 - 2024 — McMap. All rights reserved.