Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply 'or' in Clojure?

Tags:

clojure

I have a sequence of values. I want to know if any of them evaluates true.

(def input [nil nil nil 1 nil 1])

I want to do something like this:

(apply or input)

But I can't because or is a macro not a function. Similarly this won't work

(reduce or input)

I've written my own

(def orfn #(if %1 %1 %2))

And now this works

(reduce orfn input)

As does this slightly different approach, although it only tests for nil.

(not (every? nil? input))

What's the 'right' way to apply or or equivalent?

like image 416
Joe Avatar asked Dec 11 '22 09:12

Joe


2 Answers

You can use some with identity to do this:

(some identity [nil nil nil 1 nil 1])
=> 1

some returns the first truthy value from applying a function to a sequence, so this works because 1 is a truthy value.

like image 97
mikera Avatar answered Jan 23 '23 05:01

mikera


(some identity [nil nil nil nil 1 nil 1])

like image 24
Joost Diepenmaat Avatar answered Jan 23 '23 05:01

Joost Diepenmaat