将多个谓词函数组合成一个

时间:2017-08-11 20:52:27

标签: clojure functional-programming composition

是否可以撰写例如:

(defn- multiple-of-three? [n] (zero? (mod n 3))
(defn- multiple-of-five? [n] (zero? (mod n 5))

成:

multiple-of-three-or-five?

所以我可以用它来过滤:

(defn sum-of-multiples [n]
  (->> (range 1 n)
       (filter multiple-of-three-or-five?)
       (reduce +)))

另外我不想这样定义:

(defn- multiple-of-three-or-five? [n]
  (or (multiple-of-three? n)
      (multiple-of-five? n)))

例如,使用Javascript模块Ramda,它将实现为:http://ramdajs.com/docs/#either

const multipleOfThreeOrFive = R.either(multipleOfThree, multipleOfFive)

1 个答案:

答案 0 :(得分:7)

当然,在Clojure中,这是some-fn

(def multiple-of-three-or-five?
  (some-fn multiple-of-three? multiple-of-five?))
(multiple-of-three-or-five? 3)  ; => true
(multiple-of-three-or-five? 4)  ; => false
(multiple-of-three-or-five? 5)  ; => true