Emacs Lisp中的过滤函数

12

Emacs Lisp是否有类似Python或JavaScript中的高阶函数filter的等效函数?

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

==> (2 4 6 8)

2个回答

14

这就是 cl-remove-if-not。虽然有点拗口,但它很有效。

稍微解释一下,你需要

(require 'cl-lib)
为了获得这个功能。有一个别名叫做remove-if-not,但我不太喜欢使用它,因为看起来可能像我正在使用cl中的remove-if-not
在C++中,最好的做法是包括前缀,而不是使用using namespace std,每次都使用std::cout

1
在Emacs 23中,似乎没有在cl兼容包中找到remove-ifremove-if-not - Vatine
@Vatine Emacs 24也有remove-ifremove-if-not,你应该将其发布为答案,因为它们是内置的。 - jcubic
@Vatine,@jbubic:Emacs 23 中的 remove-if-not 是其 CL 兼容性功能的一部分,它在 cl-seq.el 中定义。它始终可用,无需任何 require,至少在我的经验中是这样的。也许在旧版本的 Emacs 中,默认配置没有加载 cl-seq.el - Rörd
1
在Emacs 24中它没有自动加载,你需要要求cl-lib - abo-abo

11

第三方dash.el库提供了一个-filter函数,作为cl-remove-if-not的替代选项。

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

;; => (2 4 6 8)

2
dash.el 真的是严肃的 Emacs Lisp 编程必备库 :) - user355252

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接