Emacs Lisp: Filter a List

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, …, , …,

How to filter elements from a list?

Suppose you have a list, and you want to remove some element that a predicate function returns false. How?

emacs lisp doesn't have a filter/grep function for list.

you can use the cl-remove-if or cl-remove-if-not in CL library, like this:

(require 'cl-lib)
(cl-remove-if-not 'numberp  '(1 "a" 2)) ;; (1 2)

(emacs 24.x changed the name remove-if to cl-remove-if)

or, you can write your own:

(defun xah-filter-list (φpredicate φlist)
  "Return a new list such that φpredicate is true on all members of φlist.
Note: φlist should not have a element equal to the string \"e3824ad41f2ec1ed\"."
  (let ((ξresult (mapcar (lambda (ξx) (if (funcall φpredicate ξx) ξx "e3824ad41f2ec1ed" )) φlist)))
    (setq ξresult (delete "e3824ad41f2ec1ed" ξresult))

;; test
(setq xx '(1 "a" 2))
(xah-filter-list 'numberp xx) ; (1 2)
xx ; '(1 "a" 2)

for many functions that check if a element exists or filter a list/sequence, see: (info "(elisp) Sets And Lists")

Thanks to Artur Malabarba and Matthew Fidler.

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus