In clojure, I’d like to know what are the differences between the three below.
(println (map + '(1 2 3) '(4 5 6)))
(println (map '+ '(1 2 3) '(4 5 6)))
(println (map #'+ '(1 2 3) '(4 5 6)))
The results are
(5 7 9)
(4 5 6)
(5 7 9)
I can’t understand the second one’s behavior.
I feel the first one and the third one are the same in clojure which is Lisp-1
and doesn’t distinguish between evaluating a variable and the identically named function.
This may be a basic question, but there seems not to be enough infomation. Please teach me.
Thanks.
Regarding the third case, in contrast to Common Lisp,
#'+does not read as(function +)and refer to the value of the symbol+in the function namespace, since Clojure does not have a function namespace. Instead, it reads as(var +)and refers to thevarcalled+. Applying avaris the same as applying the value stored in thevar.In the second case, you are repeatedly applying a symbol to a pair of numbers. This is valid by accident. Applying a symbol to a map is the same as indexing into that map:
If you supply a second argument, it is used as the default value in case no matching key is found in the map:
Since in each iteration, you apply the symbol
+to a pair of numbers, and since a number isn’t a map and therefore doesn’t contain+as a key, the second argument is returned as the default value of a failed match.