[Top][All Lists]

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

replace element in list

From: edgar
Subject: replace element in list
Date: Thu, 22 Nov 2018 04:42:06 +0000
User-agent: Roundcube Webmail/1.2.4


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

;; Example simple
(my-list-replace '(("a" . "b") ("c" "d")) '("c" "d") '(":)"))
;; (("a" . "b") ":)")

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

;; Example long
(setq org-latex-default-packages-alist
        (my-list-replace org-latex-default-packages-alist
                   '("T1" "fontenc" t ("pdflatex"))
                    '("" "unicode-math" t ("xelatex" "xetex"))
                    '("" "lmodern" t ("pdflatex"))
                    '("QX" "fontenc" t ("pdflatex")))))


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]