2024-11-01: Sort is a Destructive Operation

I have mostly learnt to avoid this:

* (let ((list-of-items (list 10 9 8 7 6 5 4 3 2 1)))
    (sort list-of-items #'<)
    (print (length list-of-items)))
2

SBCL's compiler does warn us:

; caught STYLE-WARNING:
;   The return value of STABLE-SORT-LIST should not be discarded.

The new head of the list is in the return value:

* (let ((list-of-items (list 10 9 8 7 6 5 4 3 2 1)))
    (setf list-of-items (sort list-of-items #'<))
    (print (length list-of-items)))
10

What keeps catching me out though is something like this:

(let ((list-of-items (list 10 9 8 7 6 5 4 3 2 1)))
  (process-list list-of-items)
  (do-some-more list-of-items))

If I put a sort within the process-list call, then the original list-of-items may be changed. So, copy-seq is needed when passing lists which we expect to be able to use later.

(Hence in Rust, you cannot reuse a variable after passing its value to a mut ref!)