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

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

Re: Chopping the last element of a list


From: Stefan Monnier
Subject: Re: Chopping the last element of a list
Date: Thu, 28 Apr 2022 19:52:11 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/29.0.50 (gnu/linux)

emacsq via Users list for the GNU Emacs text editor [2022-04-28 09:21:23] wrote:
> If I want to do this then I can do, for example:
>
> (prog1
> (car (last mylist)) (setq mylist (nbutlast mylist)))
>
> But here last and nbutlast walks the list twice unnecessarily.

Right, so you see the problem with functions like `last` and `butlast`
which work on the end of a list: they are only useful if that's the
only thing you do with that list.  As soon as you try to do more, then
you end up traversing the list multiple times.

> Shouldn't emacs provide a function which does it in one step, so the
> list isn't walked twice?
>
> E.g. (choplast mylist)

That would just suffer from the same problem you just experienced
(i.e. everytime you need to do `choplast` plus something else, you'll
end up traversing the list twice).

Instead, every time you need to work on the end of a list, you should
start by getting a reference to that end (presumably with `last` with an
appropriate N) and then you work locally on that end.


        Stefan




reply via email to

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