Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In clojure, how to apply 'and' to a list?

Tags:

In closure, how can we apply and or any other macro to a list?

This doesn't work:

(apply and '(true false)) 

Because apply can't take value of a macro.

So, what is the best way to check if all the elements of a list are true?

like image 206
viebel Avatar asked Feb 09 '12 20:02

viebel


People also ask

What does -> mean in Clojure?

It's a way to write code left to right, instead of inside out, e.g. (reduce (map (map xs bar) foo) baz) becomes (-> xs (map bar) (map foo) (reduce baz))

What is a macro in Clojure?

Clojure has a programmatic macro system which allows the compiler to be extended by user code. Macros can be used to define syntactic constructs which would require primitives or built-in support in other languages. Many core constructs of Clojure are not, in fact, primitives, but are normal macros.


2 Answers

You can do this instead:

(every? identity '(true false)) 

See this thread for more information.

like image 64
Kai Sternad Avatar answered Dec 17 '22 11:12

Kai Sternad


In Clojure macros are not first class things they don't compose quite like functions, and you cant pass them to other functions, and you can't apply them. This is because they are finished and done with before any of the applying would be done.

It is customary to wrap macros in functions to apply or pass them to functions

(defmacro my-macro [x y z] ...)  (apply #(my-macro %1 %2 %3) [1 2 3])  (map #(my-macro) [1 2 3] [:a :b :c] [a b c]) 

the anonymous-function reader macro #( makes this so easy that macroes not being first class is really not an inconvenience. Just do try to remember the first rule of macro club

like image 33
Arthur Ulfeldt Avatar answered Dec 17 '22 13:12

Arthur Ulfeldt