12

Is there equivalent of higher-order function filter in Emacs Lisp? Like function from python or Javascript.

(filter-equivalent (lambda (n) (= (% n 2) 0)) '(1 2 3 4 5 6 7 8))

==> (2 4 6 8)
Drew
  • 29,895
  • 7
  • 74
  • 104
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 1
    possible duplicate of [lisp filter out results from list not matching predicate](http://stackoverflow.com/questions/2234860/lisp-filter-out-results-from-list-not-matching-predicate) – Mirzhan Irkegulov Aug 03 '14 at 19:21

2 Answers2

14

It's cl-remove-if-not. A bit of a mouthful, but it works.

To elaborate a bit, you need

(require 'cl-lib)

to get this function. There's an alias for it, called remove-if-not, but I prefer not to use it, since it may look like I'm using remove-if-not from cl.

It's a good practice to include the prefix, not doing using namespace std in C++, but saying std::cout each time.

abo-abo
  • 20,038
  • 3
  • 50
  • 71
  • 1
    In Emacs 23, there seems to be a `remove-if` and `remove-if-not` not in the cl compatibility package. – Vatine Sep 25 '13 at 09:59
  • @Vatine Emacs 24 have `remove-if` and `remove-if-not` too, you should post it as answer because those are built in. – jcubic Sep 25 '13 at 10:52
  • @Vatine, @jbubic: The `remove-if-not` in Emacs 23 is part of its CL compatibility features, it's defined in `cl-seq.el`. It is always available without the need to `require` anything, though, at least in my experience. Maybe in older Emacs versions, `cl-seq.el` wasn't loaded by the default configuration? – Rörd Sep 25 '13 at 11:16
  • 1
    It's not autoloaded in Emacs 24, you have to require `cl-lib`. – abo-abo Sep 25 '13 at 11:22
11

The third-party dash.el library provides a -filter function as an alternative to cl-remove-if-not.

(-filter 'evenp '(1 2 3 4 5 6 7 8))

;; => (2 4 6 8)
Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117
  • 2
    dash.el is really a must-have library for serious Emacs Lisp programming :) –  Sep 26 '13 at 16:12