Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 727
unj2 Avatar asked Oct 07 '09 00:10

unj2


2 Answers

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

like image 56
James P Avatar answered Sep 17 '22 13:09

James P


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}
like image 39
konr Avatar answered Sep 18 '22 13:09

konr