unj2
unj2

Reputation: 53531

How do you convert a list of numbers into a map?

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?

Upvotes: 6

Views: 4399

Answers (5)

user4813927
user4813927

Reputation:

Just another way, which retains the original order of the keys (up to 9 keys!):

(defn list-to-map [& n] (->> (map vector n (repeat 0)) (into (hash-map))))

(list-to-map 1 2 3 4) => {1 0, 2 0, 3 0, 4 0}

(list-to-map 4 3 2 1) => {4 0, 3 0, 2 0, 1 0}

Upvotes: 0

grinnbearit
grinnbearit

Reputation: 203

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)))

Upvotes: 1

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91577

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.

Upvotes: 1

konr
konr

Reputation: 1194

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}

Upvotes: 1

James P
James P

Reputation: 1188

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 :)

Upvotes: 15

Related Questions