[英]How do you compose two or more predicates in clojure?
I want to apply two (or more) predicates to a single value. 我想将两个(或更多)谓词应用于单个值。 For example, say I want to test if a value is a positive integer: 例如,假设我想测试一个值是否为正整数:
(defn posint? [n]
(and (integer? n) (pos? n)))
That does it, but what if I want to compose the predicates applied? 这样做,但如果我想组成应用的谓词怎么办? I don't want to write a function for each possible combination of predicates. 我不想为每个可能的谓词组合编写函数。
If you're looking to do these checks inline, the following may be what you are looking for. 如果您希望内联进行这些检查,可能会出现以下情况。
(defn predicate-test [fns t]
"test all predicates against value t and return true iff all predicates return true."
(every? true? ((apply juxt fns) t)))
(predicate-test [integer? pos?] 4)
You could then create named versions for your most used predicate tests: 然后,您可以为最常用的谓词测试创建命名版本:
(def posint? (partial predicate-test [integer? pos?])
(posint? 4)
If you want to compose them in an and
relationship, use every-pred
: 如果你想在一个and
关系中组合它们,请使用every-pred
:
((every-pred pos? even?) 5)
;false
((every-pred pos? even?) 6)
;true
((every-pred pos? even?) -2)
;false
And if you want to compose them in an or
relationship, use some-fn
: 如果你想在一个or
一个关系中组成它们,请使用some-fn
:
((some-fn pos? even?) 5)
;true
((some-fn pos? even?) 6)
;true
((some-fn pos? even?) -2)
;true
((some-fn pos? even?) -3)
;false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.