开发者

"reduce" or "apply" using logical functions in Clojure

I cannot use logical functions on a range of booleans in Clojure (1.2). Neither of the following works due to logical functions being macros:

(reduce and [... sequen开发者_JS百科ce of bools ...])
(apply or [... sequence of bools ...])

The error message says that I "can't take value of a macro: #'clojure.core/and". How to apply these logical functions (macros) without writing boilerplate code?


Don't -- use every? and some instead.


Michal's answer is already spot on, but the following alternative approach can be useful in similar situations whenever you want to use a macro as a function:

(reduce #(and %1 %2) [... sequence of bools ...])

Basically you just wrap the macro in an anonymous function.

There are a couple of good reasons to consider this approach:

  • There are situations where a handy function like some or every? does not exist
  • You may get better performance (reduce is likely to benefit from some very good optimisations in the future, for example applying the function directly to a vector rather than converting the vector into a sequence)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜