Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure, difference between function, quoted function and sharp-quote function

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.

like image 741
jolly-san Avatar asked Mar 18 '12 17:03

jolly-san


1 Answers

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
like image 97
Matthias Benkard Avatar answered Oct 16 '22 15:10

Matthias Benkard