[Top][All Lists]

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

Re: replace element in list

From: Robert Munyer
Subject: Re: replace element in list
Date: Fri, 23 Nov 2018 12:05:16 +0000 (UTC)

> edgar wrote:

>> (defun my-list-replace (obj orig new)
>>     "Replaces an element in a list with something else"

>> (my-list-replace '(("a" . "b") ("c" "d")) '("c" "d") (list '("hi")))
>> ;; (("a" . "b") ("hi"))

If nothing in the list matches your "orig" item, your function will
replace the _first_ item.  Did you intend that?

(my-list-replace '(("a" . "b") ("c" "d")) '("e" "f") (list '("hi")))
;; (("hi") ("c" "d"))

Stefan Monnier wrote:

> - if you do it by modifying the list in place, it means you're using
>   nasty side-effects, which are better avoided when possible
>   (especially with lists).

Good point.

> - if you want to do it without side-effects, your operation will
>   inevitably be algorithmically inefficient because a list is not
>   designed for that.

If he doesn't want to run it very frequently nor on very long lists,
moderate inefficiency is OK.

Edgar, here is one that avoids the nasty side-effects that Stefan
mentioned.  It isn't especially efficient, but it is simple and clear.
Warning: it behaves the same as your original version _only_ if there
is exactly one matching item.

(defun my-list-replace-2 (l old-item new-items)
  (apply 'append
         (mapcar (lambda (x)
                   (cond ((equal x old-item) new-items)
                         (t (list x))))

Robert Munyer
E-mail: (reverse (append '(com dot munyer at) (list (* 91837 99713))))

reply via email to

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