golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.03k stars 17.67k forks source link

proposal: slices: Add Intersect and IntersectFunc #64539

Open Delta456 opened 11 months ago

Delta456 commented 11 months ago

Proposal Details

Utility functions like Intersect and IntersectFunc for slices packages will be handy for several cases.

// Intersect returns the common elements between two slices.
func Intersect[S ~[]E](s1, s2 S) (S ~[]E) {
        var result S
    for _, item := range s2 {
        if slices.Contains(s1, item) {
            result = append(result, item)
        }
    }
}
// IntersectFunc returns the elements between two slices according to the functions.
func IntersectFunc[S ~[]E, E comparable](s1, s2 S, f func(s1, s2 E) bool) S {
    var result S
    for _, item := range s2 {
        for _, subItem := range s1 {
            if f(subItem, item) {
                result = append(result, item)
            }
        }
    }
    return result
}
earthboundkid commented 11 months ago

This is O(N^2). It should not be in the standard library.

Delta456 commented 11 months ago

This is O(N^2). It should not be in the standard library.

So only less than O(N) are allowed in the standard library so that it doesn't affect the performance?

EDIT: I wonder if this can be optimized further because what I wrote is just the prototype.

gophun commented 11 months ago

They belong in a set package.

Delta456 commented 11 months ago

They belong in a set package.

Yes, I saw that earlier but I didn't see it being further discussed so I thought no conclusion was drawn.

gophun commented 11 months ago

It's on hold pending the completion of the iterator design (#61897).