[Top][All Lists]

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

Re: replace element in list

From: edgar
Subject: Re: replace element in list
Date: Sat, 24 Nov 2018 03:01:18 +0000
User-agent: Roundcube Webmail/1.2.4

From Eric
You'll probably get a bunch of suggestions, but mine is to use `setf'
and `nth'. You can do:

(let ((orig '(("a" . "b") ("c" "d")))
      (obj  '("c" "d"))
      (new '(":)")))
  (setf (nth (cl-position obj orig :test #'equal) orig) new)

Hope that's useful.


Thank you, Eric.

From Drew
(defun toto (xs old new)
  (let ((ms  (member old xs)))
    (unless ms (error "%S is not in %S" old xs))
    (setcar ms new)

Thanks (I wonder why toto :P ).

From Stefan
My suggestion is to not do it:
- 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).
- if you want to do it without side-effects, your operation will
  inevitably be algorithmically inefficient because a list is not
  designed for that.

-- Stefan

Thank you.

From Robert
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))))

Thanks! This is great :). I didn't know that the first element would be replaced :S !!

People, you are truly great. Thank you all.


ONLY AT VFEmail! - Use our Metadata Mitigator to keep your email out of the 
NSA's hands!
$24.95 ONETIME Lifetime accounts with Privacy Features! 15GB disk! No bandwidth quotas! Commercial and Bulk Mail Options!

reply via email to

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