Suppose I have
(setq a 1 b 2)
How can I elegantly swap the values of a
and b
without using a temporary variable?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityIf memory serves me well and you're willing to use cl-lib
then:
(cl-rotatef a b)
Note that this is Common Lisp way of solving the problem.
This is the elegant idiom I use ;-).
(setq a (prog1 b (setq b a)))
prog1
.
If it's integers:
(setq a (logxor a b))
(setq b (logxor a b))
(setq a (logxor a b))
:)
(min a b)
and second to(max a b)
. This is one solution. Some will argue that this requires two comparisons when one suffices, that's right. You can handle it with one comparison in more functional manner still, for example using destructuring bind(cl-destructuring-bind (a . b) (if (< a b) (cons a b) (cons b a)) ...)
. This is another way.cl-destructuring-bind
is a ridiculously powerful tool for this job.