Delete only the first occurrence of an item in the list?

How to remove only the first appearance of an element in the list (elisp)?

+3
source share
3 answers

You can use this elisp (which requires cl):

(defun remove-first (elt seq)
  (let ((remove-first t))
    (remove-if (lambda (e) (when (and remove-first (equal elt e))
                             (setq remove-first nil)
                             t))
               seq)))

Note: this makes a copy of the original list. To use side effects, try the following:

(defun remove-first* (elt seq)
  (if (equal elt (car seq))
      (cdr seq)
    (while (cdr seq)
      (if (equal elt (cadr seq))
          (progn (setcdr seq (cddr seq))
                 (setq seq nil))
        (setq seq (cdr seq))))
    seq))

Note: when the first element is deleted, it is returned only cdr, since it is always called with this type of operation:

(setq mylist (remove-first* 3 mylist))
+1
source

Common Lisp sequence editing functions ( removeand friends) accept a keyword argument :count:

, , ; , , , , , , , . , , . count nil, .

:

ELISP> (require 'cl)
cl

ELISP> (remove* 1 '(1 2 1 3 1 4) :count 1)
(2 1 3 1 4)

ELISP> (remove* 1 '(1 2 1 3 1 4) :count 2)
(2 3 1 4)

ELISP> (remove* 1 '(1 2 1 3 1 4) :count 2 :from-end t)
(1 2 3 4)

( , Emacs remove, cl remove*.)

+7

Noob code for elisp. positioncan be found at cl-seq.el.

(defun remove-first (elem lst)
  (interactive)
  (if (equal (position elem lst) nil ) (progn (setq lst lst) )
  (progn
  (setq out1 (nthcdr (+ 1 (position elem lst)) lst))
  (setq out2 (nbutlast lst (- (length lst) (position elem lst) ) ) )
  (delq nil (append out2 out1))
  ))
)

To remove 3 from the list, invoked as

>(setq mylist '(1 2 3 4 3 3))
>(setq mylist (remove-first 3 mylist))
(1 2 4 3 3)
+2
source

Source: https://habr.com/ru/post/1781257/


All Articles