emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Why aren't there functions such as filter, take-while, etc. "by defa


From: Drew Adams
Subject: RE: Why aren't there functions such as filter, take-while, etc. "by default"?
Date: Sun, 25 Apr 2010 15:56:15 -0700

> `sort' which given a list and a predicate sorts the list
> destructively (rendering the original list useless) and then returns a
> sorted copy of the original list.

`sort' does not return a copy. It returns the sorted list, that is, the modified
list.

,----
| sort is a built-in function in `C source code'.
| 
| (sort LIST PREDICATE)
| 
| Sort LIST, stably, comparing elements using PREDICATE.
| Returns the sorted list.  LIST is modified by side effects.
          ^^^^^^^^^^^^^^^           ^^^^^^^^
| PREDICATE is called with two elements of LIST, and should return non-nil
| if the first element should sort before the second.
| 
| [back]
`----

> (let* ((my-list (list 3 2 1))
>        (sorted (sort my-list '<)))
>   my-list) ;; returns (3)

The sorted list is (1 2 3). If your sexp returned `sorted' instead of `my-list'
then that is what you would get.

Your sexp returns (3) because `my-list' points to the cons cell whose car is 3,
and after sorting that same cons cell is the last one in the sorted list. If
`sort' returned a complete copy, then its result (`sorted') would not share any
list structure with the original list. Try this, and you will see that `sorted'
is (1 2 5). The last cons cell in `sorted' is the cons cell pointed to by
`my-list'.

(let* ((my-list (list 3 2 1))
       (sorted (sort my-list '<)))
  (setcar my-list 5)
  (message "sorted: %S" sorted) (sit-for 3) ; (1 2 5)
  my-list) ; returns (5)





reply via email to

[Prev in Thread] Current Thread [Next in Thread]