Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create map when you have a vector of keys and values

Tags:

clojure

I'm sure this is easy but i suspect i'll have a lot of little questions on the road to idomatic clojure. Maybe I missed something but looking at the clojure map page, I didn't find a solution.

Given two vectors (one of keys other of values) how do you efficiently (key word!) create a map from key to value?

The keys and values are below:

(:year :month :day) (core/split "2013-02-18" #"-")
like image 331
Core Avatar asked Jul 20 '13 09:07

Core


People also ask

Can vector keys be map?

map uses vector as the key It is not a hash table, so it doesn't need that the key is hashable. However, it requires that the key support <, >, or == operations.

Can vector be key in C++ map?

In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.

Can keys be pairs in maps?

So, you can use pair as a key in a map as follows: map<pair<int,string> , long> mp; mp.


2 Answers

The natural solution is to use zipmap:

(zipmap [:year :month :day] (clojure.string/split "2013-02-18" #"-"))
;= {:day "18", :month "02", :year "2013"}

For a small map like this it is actually pretty efficient. For a larger map, you'd want zipmap to use transients, which it currently doesn't. There's a ticket for that in JIRA, with my patch attached: CLJ-1005.

Of course it's simple enough to include the transient-enabled zipmap in one's own codebase and use it in preference to the one in clojure.core. This is a pretty important thing to do if you're zipping up larger maps.

The code can be copied over from the patch or from the ClojureScript core library, which does use transients in its zipmap; here a link to the ClojureScript source as of release 1844 (this particular function can be used in Clojure with no changes).

like image 63
Michał Marczyk Avatar answered Sep 30 '22 20:09

Michał Marczyk


What you are looking for is zipmap

like image 43
DanLebrero Avatar answered Sep 30 '22 20:09

DanLebrero