2
votes

I'm trying to write a function in clojure that calls a condition for each value in a vector; the function should return the OR of the result of the condition applied to each value. Eg I have a vector [1 2 3 4] and a condition (>= x 3) where x is an element in the vector, then the function should return true (similary [0 1 0 1] should return false).

I wrote the method

(defn contains-value-greater-or-equal-to-three [values]
    (or (for [x values] (>= x 3)))
) 

but for the vector [1 2 3 4] this just yields (false false true true); what I want instead is the 'or' function applied to these values.

I'm quite new to functional programming and clojure, let me know if I'm thinking about this the wrong way.

1

1 Answers

7
votes

Have a look at the function some, that takes a predicate and a collection as arguments, and returns true iff the predicate returns true for some item in the collection.

(some #(>= % 3) [1 2 3 4]) ; => true
(some #(>= % 3) [0 1 0 1]) ; => false

The problem with your method is that for returns a sequence of true/false values, while or expects a number of individual arguments. Given only one argument, or will return that. What you could have done is to reduce the sequence returned by for, like this:

(reduce #(or %1 %2) (for [x values] (>= x 3)))

(since or is a macro, not a function, (reduce or ...) will not work.