Hi all, I have this function requirement:
@spec group_by_chunk_index([MyStruct]) :: %{
required(integer()) => [MyStruct]
}
Which takes in a list of structs and groups them into a map where the keys are an integer representing some transformation over a struct field. For example, my struct has the field weights
which is [integer()]
. I want to loop over these structs, extract the weights for each one, transform those weight values, and group them into a new map using the transformed values as keys. For example:
first = MyStruct.new(weights: [0])
second = MyStruct.new(weights: [1])
third = MyStruct.new(weights: [5])
wanted = %{
1000 => [first, second],
2000 => [third]
}
assert group_by_chunk_index([first, second, third]) == wanted
Where any weight in the range [0-5) is mapped to the number 1000, [5, 10) to the number 2000, etc. My current approach involves an ugly series of Enum.reduce calls with a map as an accumulator. The only functions I use are Enum.reduce and Map.get_and_update. Is there a more functional approach I can take here perhaps using some other special operations from the Enum or List libraries? Thank you in advance.