Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-macro versions of clojure "and" and "or"

Tags:

clojure

Are there non-macro versions of and and or in Clojure?

Update: In this case I don't care about the short circuiting.

like image 576
pauldoo Avatar asked Apr 03 '11 19:04

pauldoo


3 Answers

or

The function some "Returns the first logical true value of (pred x) for any x in coll, else nil."

So you could use (some identity coll) for or. Note that its behaviour will differ from or when the last value is false: it will return nil where or would return false.

and

If you don't need to know the value of the last form in the coll vector, you can use (every? identity coll) for and. This will differ from the behaviour of the and macro in that it returns true if all of its arguments are truthy. See larsmans' answer if you need the result of the last form.

like image 61
intuited Avatar answered Sep 27 '22 22:09

intuited


Let land stand for "logical and", then they're trivial to define:

(defn land
  ([] true)
  ([x & xs] (and x (apply land xs))))

Or, slightly closer to the standard and behavior:

(defn land
  ([] true)
  ([x] x)
  ([x & xs] (and x (apply land xs))))

And similarly for or.

like image 42
Fred Foo Avatar answered Sep 27 '22 20:09

Fred Foo


This actually came up as a topic on clojure-dev recently. Rich Hickey ultimately concluded they should be added to core for 1.3 as every-pred and any-pred (logged as CLJ-729). I think further discussions there have led them to now be called every-pred (the and variant) and some-fn (the or variant). The final version was just recently committed to master.

like image 33
Alex Miller Avatar answered Sep 27 '22 21:09

Alex Miller