Compose multiple predicate functions into one

杀马特。学长 韩版系。学妹 提交于 2019-12-23 10:06:41

问题


Is it possible to compose for example:

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

into:

multiple-of-three-or-five?

so I can use it for filtering:

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

Also I don't want to define it like this:

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

For example with Javascript module Ramda it would be achieved as: http://ramdajs.com/docs/#either

const multipleOfThreeOrFive = R.either(multipleOfThree, multipleOfFive)

回答1:


Sure, in Clojure this is 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


来源:https://stackoverflow.com/questions/45643579/compose-multiple-predicate-functions-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!