Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In clojure, what function are symbols cast to? Why does ('+ 2 2) = 2?

Tags:

clojure

Playing around with Clojure, I noticed that ('+ 2 2) didn't throw an error like I would've expected--it returns 2. I've spent a few minutes playing around:

(def f (cast clojure.lang.IFn 'a-symbol))
(f 5)     ;; => nil
(f 5 5)   ;; => 5
(f 5 5 5) ;; ArityException Wrong number of args (3) passed to: Symbol
(f "hey")             ;; => nil
(f "foo" "bar")       ;; => "bar"
(f "foo" "bar" "baz") ;; => ArityException Wrong number of args (3) passed to: Symbol

As far as I can tell, symbols are being cast to some function with the name Symbol, that takes two arguments and returns the second one. I'm guessing it has something to do with the implementation of the symbol class?

like image 460
John Swanson Avatar asked Dec 25 '22 19:12

John Swanson


1 Answers

When called as a function symbols (like keywords) look them selves up in the map passed as the second argument

user> (def my-map '{a 1 b 2 c 3})
#'user/my-map
user> ('a my-map)
1
user> ('a my-map :not-found)
1
user> ('z my-map :not-found)
:not-found

and return the third argument, if it was passed, to indicate when nothing was found. In your example when you look up a symbol in something that is not a map, for instance the number 5, it doesn't find it:

user> ('z 4 :not-found)
:not-found
user> ('z 'z :not-found)
:not-found 

And returns the third argument, or nil if no third argument was passed.

like image 112
Arthur Ulfeldt Avatar answered May 09 '23 20:05

Arthur Ulfeldt