Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 [... sequence 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?

like image 582
Alex B Avatar asked May 23 '10 12:05

Alex B


People also ask

What is reduce in Clojure?

Reduces a collection using a (potentially parallel) reduce-combine strategy. The collection is par... Added by jcburley. clojure.core/partition-by. Applies f to each value in coll, splitting it each time f returns a new value.

Is reduce lazy Clojure?

Reducers provide an alternative approach to using sequences to manipulate standard Clojure collections. Sequence functions are typically applied lazily, in order, create intermediate results, and in a single thread.


2 Answers

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

like image 110
Michał Marczyk Avatar answered Sep 18 '22 15:09

Michał Marczyk


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)
like image 39
mikera Avatar answered Sep 18 '22 15:09

mikera