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

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

Re: Easy to add with push but not to the end of a list


From: Emanuel Berg
Subject: Re: Easy to add with push but not to the end of a list
Date: Wed, 30 Nov 2022 20:30:24 +0100
User-agent: Gnus/5.13 (Gnus v5.13)

Michael Heerdegen wrote:

>> Although it is easy to add to a list using push, it
>> currently looks hideous to be able to add to the end of
>> a list.
>
> In addition to what has already been said: if you store and
> update the last cdr of your list (in a variable for
> example), you can add something to the end of the list in
> O(1). The cost is the cost of maintaining additional data.

You can write a function that does all of that automatically
for you but then you are restricted to using such tailor-made
functions. If you couple those functions with the data they
are to manipulate you have already a small OO system with
methods and members ...

So use `push' and provide a "push-last" and say in the
docstring it's not as fast is better ...

;;; -*- lexical-binding: t -*-
;;
;; this file:
;;   https://dataswamp.org/~incal/emacs-init/list.el

(defmacro push-last (elem lst)
  "Push ELEM to be the last element of LST.
Beware that this is O(n) while `push' is O(1)."
  (if (and (symbolp lst)
           (not (symbol-value lst)) )
      (list 'setq lst `(list ,elem))
    (list 'nconc lst `(list ,elem)) ))

-- 
underground experts united
https://dataswamp.org/~incal




reply via email to

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