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" #"-")
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.
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.
So, you can use pair as a key in a map as follows: map<pair<int,string> , long> mp; mp.
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).
What you are looking for is zipmap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With