emacs-devel
[Top][All Lists]
Advanced

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

Re: Side effects of `sort'


From: Tassilo Horn
Subject: Re: Side effects of `sort'
Date: Thu, 01 Mar 2012 21:52:56 +0100
User-agent: Gnus/5.130004 (Ma Gnus v0.4) Emacs/24.0.94 (gnu/linux)

Daniel Schoepe <address@hidden> writes:

Hi Daniel,

> according to describe-function, `sort' modifies its input list, but
> not in any way that the programmer can rely on. (For example, '(2 1 3)
> becomes '(2 3)). I assume the precise thing that ends up in the
> original list is an implementation detail and being able to "destroy"
> the original list has some performance benefits.
>
> Personally, I find this behavior very surprising and think it would make
> more sense to either set the input list to the final sorting result (in
> addition to returning it) or not to modify the input.

That's the point of all destructive operations like sort, nconc,
nreverse and so forth.  The perform better, because they don't copy but
only rearrange pointers in their input, and you must always use the
return value.

In your example, foo points to the list (2 1 3), i.e., foo is a pointer
to the cons cell (2 . cdr).

  foo -> (2 . (1 . (3 . nil)))

2 is bigger than 1, so we can make the 1-cons-cdr point to the 2-cons,
and the 2-cons-cdr point to the cdr of the 1-cons.

  (1 . (2 . (3 . nil)))
       ^
       |
      foo

However, the variable foo still points to the original cons cell (2
. cdr).  See?

Bye,
Tassilo



reply via email to

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