help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: Adding many elements to a list


From: David Kastrup
Subject: Re: Adding many elements to a list
Date: Fri, 18 Sep 2009 15:52:40 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1.50 (gnu/linux)

Nordlöw <per.nordlow@gmail.com> writes:

> What is the most efficient way of performing lots of successive
> appends of elements to the same list?
>
> If we start with defining the list
>
> (setq l '(a b))
>
> then the Emacs manual says that we can use
>
> (nconc l '(c d)))

Where?  That's merely a side-effect.  As a stylistic rule of thumb, you
should not use nconc where concat would not also do the trick.  So in
this case, the proper usage would be

(setq l (nconc l '(c d)))

However, this particular use case is almost certainly _wrong_.  nconc is
a destructive operator, you should only use it on lists that were
constructed (consed) under _your_ control.  In this case, '(c d) has
been constructed under the control of the Lisp reader instead.  Using
nconc on it is certain to lead to trouble eventually.  To wit:

(setq l '(a b))
(dotimes (i 3) (nconc l '(c d)))

*Booooom*

Can you see what happens here?

If you don't have a clue about the ramifications of nconc, don't use it.

> I have noticed that this works in all cases except when l is nil.
> To make this case work aswell we need to do use
>
> (setq l (nconc l '(c d))))
>
>
> Or can we use setcar or setcdr in a more clever way?

nil is not a cons cell.  So there is no car or cdr to set.

-- 
David Kastrup


reply via email to

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