Elisp: cannot grasp effect of setq and sort
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
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)
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
精彩评论