tags:

views:

154

answers:

4

I have a list of keys: (1 2 3 4)

I want a map with the values set to 0 like this: {1 0, 2 0, 3 0, 4 0}. How do I do that?

+8  A: 

You could do something like this with the zipmap function:

(zipmap '(1 2 3 4) (repeat 0))
=> {4 0, 3 0, 2 0, 1 0}

zipmap takes a list of keys and a list of values and converts them into a map. The repeat function creates an infinite sequence of 0s. zipmap stops when it reaches the end of the shorter list, so just don't pass it two infinite sequences :)

James P
In my original map function, I had an additional function on the key. (map (fn[key] (foo key)..)..is there a way to incorporate that function into the zipmap or should I just apply the function before I use zipmap?
kunjaan
It shouldn't be a problem as map returns a sequence. Just replace '(1 2 3 4) with your map function: e.g. if you wanted to convert the numbers to a string before making them the key: (zipmap (map #(str %) '(1 2 3 4)) (repeat 0)) => {"4" 0, "3" 0, "2" 0, "1" 0}Is that what you mean?
James P
A: 

You can also create a function with James' zipmap:

Clojure=> (defn map-to-n [n] (zipmap (range 1 n) (repeat 0)))
#'user/map-to-n
Clojure=> (map-to-n 10)
{9 0, 8 0, 7 0, 6 0, 5 0, 4 0, 3 0, 2 0, 1 0}
konr
A: 

The more general pattern for this is to use (apply collection list to create the collection. The Clojure collections all have "constructors" or creation functions that take a variable number of arguments and return thows arguments bundled up in the collection. if your arguments are already wrapped up in another collection then apply is a convenient way to take them out of the collection and pass them to the creation function as arguments.

This is a lot more work. which is why we have wrapper functions like zipmap.

Arthur Ulfeldt
+1  A: 

Wow I didn't know about zipmap, thats useful

I would have done it like this

(apply hash-map (interleave '(1 2 3 4)  (repeat 0)))
grinnbearit