3

When evaluating the following code in Emacs, I get (2 3) as the final value of x. I'd expect (1 2 3). What am I missing?

(setq x '(2 1 3))
(sort x '<)
x

2 Answers2

8

If you read sort's documentation, you will find that it returns the sorted list, and the input list is modified by side effects. It does not say that the argument list will contain the sorted result -- It is just somehow modified by the sorting algorithm. Or, to put it shortly: sort is destructive.

So, you'll want to bind/assign sort's return value:

elisp> (setq x '(2 1 3))
(2 1 3)

elisp> (setq x (sort x '<))
(1 2 3)

elisp> x
(1 2 3)
danlei
  • 14,121
  • 5
  • 58
  • 82
  • 2
    Also, note that modifying literals destructively may have consequences you don't expect. (See for example: http://stackoverflow.com/questions/6865142/lisp-cons-and-number-number-difference/6866155#6866155, which is about CL but applies to Emacs-Lisp, too) – danlei Aug 28 '11 at 20:05
1

I don't have much experience with elisp, but it is behaving correctly due to the implementation with car and cdr. Check http://www.gnu.org/software/emacs/elisp/html_node/Rearrangement.html#Rearrangement

Pedro Montoto García
  • 1,672
  • 2
  • 18
  • 38