map - How to pair items from a nested vector with corresponding single values in Clojure? -
map - How to pair items from a nested vector with corresponding single values in Clojure? -
i'm learning clojure, , want understand more sequences. have real-life problem have reduced general one, don't know if has canonical name. illustration below makes clear.
say have 2 vectors, src
, dst
. items in src
vector vectors, , need map each item in each vector corresponding value in dst
.
(def src [ ["a1" "a2" "a3"] ["b1" "b2"] ["c1" "c2" "c3" "c4"] ]) (def dst [ "a" "b" "c" ])
i want produce next map:
{ :a1 "a", :a2 "a", :a3 "a", :b1 "b", :b2 "b", :c1 "c", :c2 "c", :c3 "c", :c4 "c" }
i can fine in python, clojure way of doing not clear me. problem, build map, want able in generic way, not instance.
in python, be:
src = [['a1', 'a2', 'a3'], ['b1', 'b2'], ['c1', 'c2', 'c3', 'c4']] dst = ['a', 'b', 'c'] result = {} (s, d) in zip(src, dst): x in s: result[x] = d
in clojure, i've tried starting with:
(interleave src dst) ;=> (["a1" "a2"] "a" ["b1" "b2" "b3"] "b" ["c1"] "c")
so i've flattened vectors, don't know how iterate on map keys, , pick values.
also, zipmap
doesn't me far itself:
(zipmap src (map keyword dst)) ;=> {["c1"] :c, ["b1" "b2" "b3"] :b, ["a1" "a2"] :a} ;bogus result
now need flip map keys , values, , still iterate.
i haven't been successful in constructing for
look either:
(for [s src] (zipmap s dst))) ;=> ({"a2" "b", "a1" "a"} {"b3" "c", "b2" "b", "b1" "a"} {"c1" "a"}) ;bogus result
i'm approaching problem pairing 2 vectors, can't seem vectors src
vector position zipmap
each of them dst
.
i suspect reply obvious, brain still not working functionally enough. maybe there into {}
and/or assoc
in there somewhere.
any pointers? if you're interested, real-life problem mentioned mapping rna codons amino acids.
map
can take multiple seqs iterate over, e.g.:
(map + [1 2 3] [4 5 6]) ;; => (5 7 9)
so, way values want process same function, resulting in processing of pairs ["a1" "a2" "a3"]
/"a"
, etc...
(map (fn [src dst] ???) [["a1" "a2" "a3"] ["b1" "b2"] ["c1" "c2" "c3" "c4"]] ["a" "b" "c"])
zipmap
takes seq of keys (which have) , seq of values (which have build single value). repeat
can used create infinite lazy seq based on constant value:
(take 3 (repeat "a")) ;; => ("a" "a" "a")
and:
(zipmap ["a1" "a2" "a3"] (repeat "a")) ;; => {"a3" "a", "a2" "a", "a1" "a"}
this makes original code this:
(map (fn [src dst] (zipmap src (repeat dst))) [["a1" "a2" "a3"] ["b1" "b2"] ["c1" "c2" "c3" "c4"]] ["a" "b" "c"]) ;; => ({"a3" "a", "a2" "a", "a1" "a"} {"b2" "b", "b1" "b"} {"c4" "c", "c3" "c", "c2" "c", "c1" "c"})
and finally, can merge of these maps single 1 using into
, resulting in final piece of code:
(into {} (map #(zipmap %1 (repeat %2)) src dst)) ;; => {"a3" "a", "c2" "c", "c3" "c", "a1" "a", "b2" "b", "c4" "c", "a2" "a", "c1" "c", "b1" "b"}
map clojure zipmap
Comments
Post a Comment