[英]clojure.core/or partial function works well with first argument but not with second
(defn可整除[xy](零?(rem xy)))
第一個表達式為真,但第二個為什么不為真?
形式(or foo bar)
的表達式不會將兩個謂詞“粘在一起”為一個復合謂詞; 如果為真,則返回foo
,否則返回bar
。 在您的代碼中, (fn [x] (divisible x 3))
可分解的(fn [x] (divisible x 3))
當然是真實的(唯一的falsey值是false
和nil
),因此整個過程等效於
((fn [x] (divisible x 3)) 3)
((fn [x] (divisible x 3)) 5)
你想要做的是
(some #(apply % 3) [(fn [x] (divisible x 3)) (fn [x] (divisible x 5)])
(some #(apply % 5) [(fn [x] (divisible x 3)) (fn [x] (divisible x 5)])
; ^- here goes the thing being tested
一般來說,
(defn or-preds [& preds]
(fn [& args]
(some #(apply % args) preds)))
((or-preds (fn [x] (divisible x 3)) (fn [x] (divisible x 5))) 3)
((or-preds (fn [x] (divisible x 3)) (fn [x] (divisible x 5))) 5)
;; or simpler...
((or-preds #(divisible % 3) #(divisible % 5)) 3)
您似乎認為or
以某種方式組合了它作為參數接收的功能,但事實並非如此。 or
可以將任何類型的值用作參數,並僅返回第一個“真實的”值。
因此(or (fn [x] (divisible x 3)) (fn [x] (divisible x 5)))
返回(fn [x] (divisible x 3))
(因為函數不是“什么都不是”,因此是“真實的” ”)。
因此,當您執行((or (fn [x] (divisible x 3)) (fn [x] (divisible x 5))) something)
,您實際上只是在做((fn [x] (divisible x 3)) something)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.