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: Michael Heerdegen
Subject: Re: Chopping the last element of a list
Date: Thu, 28 Apr 2022 23:33:03 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/29.0.50 (gnu/linux)

emacsq via Users list for the GNU Emacs text editor
<help-gnu-emacs@gnu.org> writes:

> 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.

I would do that like

#+begin_src emacs-lisp
(let ((last2 (last my-list 2)))
  (prog1 (cons (cadr last2) my-list) (setcdr last2 nil)))
#+end_src

> Is there an existing function which does this in one step? If not,
> shouldn't there be one built-in emacs, for efficient manipulation of
> the list's end?

Dunno.  Does one need that so often?

I remember that I once implemented `rotate-left' and `rotate-right'
functions for lists, but I never used them.  Most of the time you need a
pointer to the last cdr more than once, and then it is more efficient to
remember that pointer in a variable.

What's your use case?

Michael.




reply via email to

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