Clojure first and relax

Why do I have 2 different meanings for

(apply (first '(+ 1 2)) (rest '(+ 1 2))) > 2 

and

 (apply + '(1 2)) > 3 

when

 (first '(+ 1 2)) > + 

and

 (rest '(+ 1 2)) > (1 2) 

I tried to reduce and got the same value

 (reduce (first '(+ 1 2)) (rest '(+ 1 2))) > 2 
+4
source share
2 answers

Your problem is that you are trying to call the '+ character, not the + function. When you call a character, it tries to find the character in the first argument (for example, if it were {'a 1 '+ 5 'b 2} , you would get 5 ). If you pass the second argument, this value is returned instead of nil if the character cannot be found in the first argument. So when you call ('+ 1 2) , it tries to search for '+ in 1 and fails, so it returns 2.

By the way, this is the difference between creating lists with '(+ 1 2) and (list + 1 2) . The former creates a list of +, 1, and 2. Since β€œ1 and 1 is the same, that's fine. But theβ€œ + ”is not Var clojure.core / +, so the latter gets the value Var, while the first is just gets the character. So, if you did (list + 1 2) , you could work as it is written.

+8
source

(first '(+ 1 2)) is a character.

 user=> (class (first '(+ 1 2))) clojure.lang.Symbol user=> (apply (symbol "+") [1 2]) 2 user=> (apply (eval (symbol "+")) [1 2]) 3 user=> (apply (eval (first '(+ 1 2))) (rest '(+ 1 2))) 3 user=> (class (first [+ 1 2])) clojure.core$_PLUS_ user=> (apply (first [+ 1 2]) (rest '(+ 1 2))) 3 
+2
source

All Articles