groupBy with transform
feldman4 opened this issue · comments
It would be nice to have a version of groupBy
that also maps the values. This seems like a common scenario when taking apart and reassembling dictionaries, as below.
invert : Dict comparable (List comparable1) -> Dict comparable1 (List comparable)
invert dict =
let
f ( x, ys ) =
List.map (\y -> ( x, y )) ys
g _ xys =
List.map Tuple.first xys
in
dict
|> Dict.toList
|> List.concatMap f
|> Dict.Extra.groupBy Tuple.second
|> Dict.map g
Come to think of it, inverting dictionaries is also pretty common.
If I understand your example correctly, this would only save you one line of code (the last .map
)? If so, I don't see the point, to be honest.
When it comes to inverting dictionaries, you mean making the keys into values or vice versa? I could see the need for such a function.
I guess it feels inefficient to first build the dictionary, then go into each value (a list) and map all the sub-values. Earlier I was trying to speed up a slow dictionary manipulation, which I've since given up on.
Functions to invert dictionaries in general would be useful, too.