Will
Will

Reputation: 55

Clojure (map) over map keys

I've got a map from keywords to compass direction strings:

(def dirnames {:n "North", :s "South", :e "East", :w "West"})

I can look up names using the map as a function:

(dirnames :n)
;# = "North"

It seems to me that

(map dirnames [:n :s])

ought to return the vector

["North" "South"]

but it returns

[:n :s]

instead. I've tried this half a dozen ways, supplying different functions in place of "dirnames" in the (map) call, and I always get the vector of keywords back.

Clearly I'm missing something basic. What is it?

Upvotes: 1

Views: 189

Answers (2)

amalloy
amalloy

Reputation: 92087

I bet you forgot some parens. Consider this function definition:

(defn foo [dirnames]
  map dirnames [:n :s])

It looks almost right, but it evaluates map for side effects, then dirnames for side effects (both of those do nothing), and then finally returns [:n :s]. That's the only reasonable explanation I can think of for behavior like what you're describing.

Upvotes: 2

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91577

Works for me, am i misinterpreting the question:

user> (def dirnames {:n "North", :s "South", :e "East", :w "West"})\
#'user/dirnames

user> (map dirnames [:n :s])
("North" "South")

also:

user> (map #(dirnames %) [:n :s])
("North" "South")
user> (mapv #(dirnames %) [:n :s])
["North" "South"]

Upvotes: 2

Related Questions