JamesSwift
JamesSwift

Reputation: 863

Why are these Clojure lists different?

I'm running through some of the 4Clojure problems and hit some weird behavior with some of my code. Upon further investigation it seems the culprit was using the quote macro vs list function. Why does this matter in the code below, and why does it produce the incorrect result?

user=> (= (class '(/ 1 2)) (class (list / 1 2)))
true
user=> (def a '(/ 1 2))
#'user/a
user=> (def b (list / 1 2))
#'user/b
user=> (class a)
clojure.lang.PersistentList
user=> (class b)
clojure.lang.PersistentList
user=> (apply (first a) (rest a))
2
user=> (apply (first b) (rest b))
1/2
user=> (class (first a))
clojure.lang.Symbol
user=> (class (first b))
clojure.core$_SLASH_

Upvotes: 3

Views: 125

Answers (2)

mobyte
mobyte

Reputation: 3752

Unfortunately, you have used the symbol object as function in expression (apply (first a) (rest a)). The symbol object looks for the value of itself as a key in a map:

('/ {'+ :plus '/ :slash '- :minus} :not-found)
=> :slash

('/ {'+ :plus '$ :dollar '- :minus} :not-found)
=> :not-found

('/ 1 :not-found)
=> :not-found

('/ 1 2)
=> 2

Upvotes: 2

Barmar
Barmar

Reputation: 780673

'(/ 1 2)

is analogous to:

(list '/ 1 2)

When you don't quote /, you get its value, which is the built-in division function, rather than the symbol.

Upvotes: 9

Related Questions