Suppose I have
(setq a 1 b 2)
How can I elegantly swap the values of a
and b
without using a temporary variable?
This is the elegant idiom I use ;-).
(setq a (prog1 b (setq b a)))
prog1
.
– Drew
Aug 20 '15 at 19:51
If 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.
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. – Mark Karpov Aug 20 '15 at 19:59cl-destructuring-bind
is a ridiculously powerful tool for this job. – PythonNut Aug 20 '15 at 22:54