22

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.

mikera
  • 105,238
  • 25
  • 256
  • 415
jolly-san
  • 2,047
  • 2
  • 14
  • 9

1 Answers1

35

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
Matthias Benkard
  • 15,497
  • 4
  • 39
  • 47
  • 1
    Great answer. Clear explanation of not immediately obvious behavior. Thanks. – sw1nn Mar 18 '12 at 18:39
  • 1
    Thank you very much, Matthias. I could understand what #' means. I didn't realize Var, and I ignored it, but this time I could understand it more deeply. I also could understand the 2nd code behavior. Thank you. – jolly-san Mar 19 '12 at 08:04