Emacs Lisp: Filter a List

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

How to filter elements from a 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)

Note: emacs 24.x renamed remove-if to cl-remove-if

or, you can write your own:

(defun xah-filter-list (φpredicate φsequence)
  "Return a new list such that φpredicate is true on all members of φsequence.
URL `http://ergoemacs.org/emacs/elisp_filter_list.html'
Version 2015-05-23"
    (lambda (ξx)
      (if (funcall φpredicate ξx)
        "e3824ad41f2ec1ed" ))
;; test
(setq xx '(1 "a" 2))

;; returns a new list
(xah-filter-list 'numberp xx) ; (1 2)

;; old remain unchanged
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, Matthew Fidler.

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