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 the var
called +
. Applying a var
is the same as applying the value stored in the var
.
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:
user> ('a {'a 1, 'b 2, 'c 3, '+ 4})
1
user> ('+ {'a 1, 'b 2, 'c 3, '+ 4})
4
If you supply a second argument, it is used as the default value in case no matching key is found in the map:
user> ('+ {'a 1, 'b 2, 'c 3} 4)
4
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.
user> ('+ 'foo 4)
4
user> ('+ {} 4)
4
user> ('+ 1 4)
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With