2017-08-11 71 views
3

是否有可能構成例如:撰寫多個謂詞功能於一體

(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) 
+0

你需要做的'或'你可以從你的兩個現有組合中的表達式插入到一個新的'多的-三或五?'='(或(零?(mod n 3))(零?(mod n 5)))'這將消除另外的1-2個函數調用。 –

+0

是的,但想象2個更復雜的謂詞函數具有不同的含義。讓他們分開會更好。我只是想了解如何在clojure中實現(即使存在庫也是如此)。 –

+1

相關:https://stackoverflow.com/q/17259965 – glts

回答

6

,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 
+0

太棒了,那就是我需要的。 –