2017-02-15 40 views
2

我有很多謂詞函數在向量中fs,並且想要and他們都在一起。這工作前兩個功能:如何應用每一個謂詞函數(`和`他們)

((and (first fs) (second fs)) value) 

不過,我想編寫適用於and所有功能,無論有多少代碼。 (apply and fs)不編譯,因爲and是一個宏。

對於謂詞函數and工作爲例,試試這個:

((and number? integer?) 1) 

編輯如果你不看評論,都and結構上面是壞榜樣。對於實際工作的相同結構,使用every-pred而不是and

+0

你有沒有嘗試把它們放在'do'塊中? – jmargolisvt

+0

不 - 不知道該怎麼做,或者爲什麼會想要 - 沒有副作用 –

+0

我編輯了我的答案。我很確定每個pred都完全符合你的要求。 – RedDeckWins

回答

3

由於您使用謂詞,every-pred可能是感興趣的。

閱讀完編輯之後 - 謝謝,我不知道,你可以用and來做到這一點。另外我已經編輯我的答案,我想你一定要應用的每個-預解碼

((apply every-pred [number? integer?]) 1) 
=> true 
((apply every-pred [number? integer?]) "asdf") 
=> false 
+0

我修好了,對不起。 – RedDeckWins

+0

爲了明確,所需的函數是'(部分應用每個pred)'。 – Thumbnail

1

它看起來像every-pred是一個很好的回答這個問題(我以前沒有注意到這一點!)。 A related function that may be handyjuxt。它適用於多種功能於一個參數:

((juxt a b c) x) => [(a x) (b x) (c x)] 

需要注意的是,不像every-predjuxt功能不短路,並始終計算列表中的每個功能。舉個例子:

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

這不會給你你正在尋找的結果。