Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: slices: Add Intersect and IntersectFunc #64539

Open
Delta456 opened this issue Dec 4, 2023 · 5 comments
Open

proposal: slices: Add Intersect and IntersectFunc #64539

Delta456 opened this issue Dec 4, 2023 · 5 comments
Labels
Milestone

Comments

@Delta456
Copy link

Delta456 commented Dec 4, 2023

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
}
@gopherbot gopherbot added this to the Proposal milestone Dec 4, 2023
@earthboundkid
Copy link
Contributor

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

@Delta456
Copy link
Author

Delta456 commented Dec 4, 2023

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
Copy link

gophun commented Dec 4, 2023

They belong in a set package.

@Delta456
Copy link
Author

Delta456 commented Dec 4, 2023

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
Copy link

gophun commented Dec 4, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

4 participants