开发者

Elisp: cannot grasp effect of setq and sort

开发者 https://www.devze.com 2023-03-31 03:06 出处:网络
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?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号