它看起來像every-pred
是一個很好的回答這個問題(我以前沒有注意到這一點!)。 A related function that may be handy是juxt
。它適用於多種功能於一個參數:
((juxt a b c) x) => [(a x) (b x) (c x)]
需要注意的是,不像every-pred
的juxt
功能不短路,並始終計算列表中的每個功能。舉個例子:
(ns tst.clj.core
(:use clj.core clojure.test tupelo.test)
(:require [tupelo.core :as t]))
(defn f2 [x] (zero? (mod x 2)))
(defn f3 [x] (zero? (mod x 3)))
(defn f5 [x] (zero? (mod x 5)))
(def f235 (apply juxt [f2 f3 f5]))
這給我們的結果:
(f235 2) => [true false false]
(f235 3) => [false true false]
(f235 5) => [false false true]
(f235 6) => [true true false]
(f235 10) => [true false true]
(f235 15) => [false true true]
(f235 30) => [true true true]
(every? truthy? (f235 15)) => false
(every? truthy? (f235 30)) => true
其中truthy?
功能類似於boolean
:
(defn truthy?
"Returns true if arg is logical true (neither nil nor false); otherwise returns false."
[arg]
(if arg true false))
附:請注意,您的原始示例不會說(and (f1 x) (f2 x))
,而是說(and f1 f2) => f1
。所以當你鍵入
(def fs [f1 f2 f3 f4])
((and (first fs) (second fs)) value)
=> ((and f1 f2) value)
=> (f1 value)
這不會給你你正在尋找的結果。
你有沒有嘗試把它們放在'do'塊中? – jmargolisvt
不 - 不知道該怎麼做,或者爲什麼會想要 - 沒有副作用 –
我編輯了我的答案。我很確定每個pred都完全符合你的要求。 – RedDeckWins