Elisp: Sequence Filter

By Xah Lee. Date: . Last updated: .

Filter by Function

seq-filter
(seq-filter PRED SEQUENCE)

get items where function PRED return true. Original unchanged.

seq-remove
(seq-remove PRED SEQUENCE)

remove items where function PRED return true. Original unchanged.

(setq xx (list "some" "thing" "in" "water"))

;; remove items that contains letter i
(seq-remove (lambda (x) (string-match "i" x)) xx)
;; ("some" "water")

Filter with Transform

seq-keep

(seq-keep FUNCTION SEQUENCE)

apply a function, return a list of all function's results that's not nil.

this is like transform and filter in one.

(setq xx (vector 1 2 3 4 5 6))

;; get all even elements, convert to string, prepend x
(seq-keep
 (lambda (x)
   (if (eq (mod x 2) 0)
       (format "x%s" x)
     nil))
 xx)
;; ("x2" "x4" "x6")

Remove by Equality Test

remove
(remove x sequence)
  • Remove all x in sequence.
  • The original sequence is unchanged.
  • Returns a new sequence.
  • Comparison is done with equal. 〔see Elisp: Equality Test
(setq xx '(3 4 5))
(remove 4 xx) ;; (3 5)
xx ; (3 4 5)
delete
(delete x sequence)
  • Remove all x in sequence.
  • The original sequence is destroyed if it's a list.
  • Returns a new sequence.
  • Comparison is done with equal. 〔see Elisp: Equality Test
(setq xx '(3 4 5))

;; always set result to the same var. because original is usually destroyed
(setq xx (delete 4 xx)) ; (3 5)

;; on vector
(setq xx [3 4 5])
(setq xx (delete 4 xx)) ; [3 5]

Delete Duplicates

seq-uniq
(seq-uniq SEQUENCE &optional TESTFN)
  • Get unique elements.
  • Return a list.
  • by default, comparison is done with equal. 〔see Elisp: Equality Test
(seq-uniq [7 8 6 8 8])
;; (7 8 6)
(seq-uniq [7 8.0 6 8 8] '=)
;; (7 8.0 6)

(seq-uniq [7 8.0 6 8 8] )
;; (7 8.0 6 8)

Elisp, sequence functions