Dropless · 2022-11-19 10:56
I've been reading gnu's manul on elisp recently. In [sort function](https://www.gnu.org/software/emacs/manual/html_node/elisp/Sequence-Functions.html#index-sort), it talked on `sort` being destructive.
> (setq nums (list 1 3 2 6 5 4 0))
> ⇒ (1 3 2 6 5 4 0)
>
> (sort nums #'<)
> ⇒ (0 1 2 3 4 5 6)
>
> nums
> ⇒ (1 2 3 4 5 6)
Well, I understand this because it is a linked list and `nums` points to the cell that contains `1`. To get the sorted list, we have to store the result back:
`(setq nums (sort nums #'<))`.
However, with doing this it said:
>**Most often** we store the result back into the variable that held the original list
It's "Most often". So it means it's not 100% reliable, right? And why is that? I suppose sorting a list is a fundamental functionality in most languages. If it's not 100% reliable, what is the best practice to sort a list in elisp?
Thank you!
yyoncho · 2022-11-19 11:00
> It's "Most often". So it means it's not 100% reliable, right?
It means that you should use the result and you should not rely on the original variable being sorted.
agrostis · 2022-11-19 11:13
> you should not rely on the original variable being sorted
IMHO, it would be more accurate to say that one should not rely on the original variable pointing to the same cons cell as the result of ``sort``. The head cell of the original list can end up in the middle of the sorted list; with the cells linked from it, it *shall* form a sorted sequence, though it won't necessarily have all the elements of the original list.
Dropless · 2022-11-19 11:25
Oh, right. I'm feeling stupid. Thanks for help.
7890yuiop · 2022-11-19 22:38
The quote was:
> Don’t assume a variable that formerly held the argument now holds the entire sorted list! Instead, save the result of `sort` and use that. Most often we store the result back into the variable that held the original list: `(setq nums (sort nums #'<))`
The code snippet at the end is part of the last sentence, and "Most often we..." is referring to the behaviour of the *programmer*, rather than the *program*.