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?
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?
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 :)
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}
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.
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)))