【发布时间】:2015-01-10 06:49:06
【问题描述】:
我有一个更高阶的谓词
(defn not-factor-of-x? [x]
(fn [n]
(cond
(= n x) true
(zero? (rem n x)) false
:else true)))
返回一个谓词,检查给定参数 n 是否不是 x 的因子。 现在我想过滤一个数字列表并找出哪些不是说'(2 3)的因素。一种方法是:
(filter (not-factor-of-x? 3) (filter (not-factor-of-x? 2) (range 2 100)))
但是一个人只能输入这么多。为了动态地做到这一点,我尝试了函数组合:
(comp (partial filter (not-factor-of-x? 2)) (partial filter (not-factor-of-x? 3)))
而且它有效。所以我尝试减少过滤器,如下所示:
(defn compose-filters [fn1 fn2]
(comp (partial filter fn1) (partial filter fn2)))
(def composed-filter (reduce compose-filters (map not-factor-of-x? '(2 3 5 7 11))))
(composed-filter (range 2 122)) ; returns (2 3 4 5 6 7 8 9 10 .......)
那么,为什么过滤器组合没有按预期工作?
【问题讨论】:
-
怎么样 (remove (factor-of-x? ...) ...) 而不是 (filter (NOT-factor-of-x? ...) ...)跨度>
标签: clojure functional-programming higher-order-functions function-composition