Open
Description
Proposal Details
I propose to add the functions Group
and GroupFunc
to the package maps , as I find myself reimplementing these often.
They work similarly to Object.GroupBy
in JavaScript.
func Group[K comparable, V any](seq iter.Seq2[K, V]) map[K][]V {
m := make(map[K][]V)
for k, v := range seq {
s := m[k]
s = append(s, v)
m[k] = s
}
return m
}
func GroupFunc[K comparable, V any](seq iter.Seq[V], f func(V) K) map[K][]V {
m := make(map[K][]V)
for v := range seq {
k := f(v)
s := m[k]
s = append(s, v)
m[k] = s
}
return m
}
Metadata
Metadata
Assignees
Type
Projects
Status
Incoming
Milestone
Relationships
Development
No branches or pull requests
Activity
adonovan commentedon Apr 22, 2024
What's a typical implementation of Seq2 in this scenario? (Often a Seq2 is a map, which doesn't have repeated keys.)
leb-kuchen commentedon Apr 22, 2024
adonovan commentedon Apr 22, 2024
PersonAll
is not an obvious iterator, because the first element (K=string) is redundant with the second (V=Person), and is not a primary key. Do we expect this kind of thing to be common?leb-kuchen commentedon Apr 22, 2024
Group
is definitely less common thanGroupFunc
and this example can also be expressed withGroupFunc
, but it has its use cases.earthboundkid commentedon Apr 23, 2024
Assume we have a
people.All()
iterator of some kind.Would using a helper function save much here? Sometimes a loop is more clear than a helper function.
leb-kuchen commentedon Apr 23, 2024
For simple use cases like this, I think
GroupFunc
is more idiomatic. If name was a getter, you would have to use a variable. This conveys its meaning more clearly.Object.groupBy
was originally intended to beArray.prototype.group
and was only changed due web compatibly issues. So there seems to be a demand for this kind of function. The iterator also supports simple use cases like Limit and Filter. Of course you can say that a loop is idiomatic, but this could be said about every higher order function.jimmyfrasche commentedon Aug 29, 2024
A generalization of
GroupBy
isGroupReduce[K comparable, S, T any](sum S, reduce func(S, T) S, seq iter.Seq2[K, T]) map[K]S
which makesGroupBy
's implementationGroupReduce(nil, append, seq)
(you need a wrapper around append to get it to work but I'm being a bit loose here to get the point across).earthboundkid commentedon Aug 29, 2024
Cross linking #69123, which is also about a grouping iterator.
jimmyfrasche commentedon Aug 29, 2024
I'm not sure about
GroupFunc
. I see the utility but it seems to be fusing two operations.If there were a
that yields
(key(v), v)
thenGroupFunc
would just bereturn GroupBy(KeyBy(key, seq))
but then againKeyBy
is trivial to write in terms ofMap21
#61898 (comment)