elixir - Create lists of list while creating a map -
i wrote
enum.reduce(list, map, fn elem, map -> key=hd(elem) map.put(map, key, list.wrap(map.get(map, key)) ++ tl(elem)) end) the list looks this
['b2', ['b1', 'b2', 'b3']], ['b2', ['a1', 'a2', 'a3']], and desired result looks like
b2 => [['b1', 'b2', 'b3'], ['a1', 'a2', 'a3']] the above code produce result feels exceptionally ugly.
i feel enum.into work nicer variant seems can't hold of values meanwhile. have tried
enum.into(list, map, fn [k, v] -> {k, list.wrap(map.get(map, k)) ++ v} end ) but doesn't produce useful. believe brain has hard time coming off imperative mindset have used in last quarter century of coding.
i'd use enum.reduce/3 well, instead of map.put/3 + list.wrap/1, i'd use map.update/4 , instead of hd/1 , tl/1 pattern matching.
list = [ ['a2', ['b1', 'b2', 'b3']], ['a2', ['a1', 'a2', 'a3']], ['b2', ['b1', 'b2', 'b3']], ['b2', ['a1', 'a2', 'a3']], ] list |> enum.reduce(%{}, fn [k | v], acc -> map.update(acc, k, v, &(&1 ++ v)) end) |> io.inspect output:
%{'a2' => [['b1', 'b2', 'b3'], ['a1', 'a2', 'a3']], 'b2' => [['b1', 'b2', 'b3'], ['a1', 'a2', 'a3']]}
Comments
Post a Comment