Clojure (map) over map keys

194 Views Asked by At

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?

2

There are 2 best solutions below

2
On

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.

1
On

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"]