[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: replace element in list
From: |
Eric Abrahamsen |
Subject: |
Re: replace element in list |
Date: |
Wed, 21 Nov 2018 21:18:22 -0800 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux) |
edgar@openmail.cc writes:
> Hello,
>
> I want to share and know if there is a better way (more efficient or
> clearer) to replace something within a list (I don't know LISP). My
> code is like this, and it works for the given example.
>
> (defun my-list-replace (obj orig new)
> "Replaces an element in a list with something else"
> (let* (
> ;; Position of the thing we need to remove
> (pos (cl-position orig obj :test 'equal))
> ;; If pos is nil, reset to zero
> (pos (if pos pos 0))
> ;; The length of the original object
> (objlen (length obj))
> ;; The elements before the element to remove
> (head (butlast obj (- objlen pos)))
> ;; The elements after the element to remove
> (trail (nthcdr (+ 1 pos) obj)))
> ;; Join (1) the sub-list before the element to be replaced
> ;; with (2) the new element and (3) the rest of the list
> (append head (append new trail))
> ))
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)
orig)
Hope that's useful.
Eric