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

Add slices.Any, slices.None #2

Closed
cloudshiftchris opened this issue Feb 20, 2023 · 3 comments
Closed

Add slices.Any, slices.None #2

cloudshiftchris opened this issue Feb 20, 2023 · 3 comments

Comments

@cloudshiftchris
Copy link

Any and None are useful constructs to determine if any (or none) of the elements match a predicate.

Sample implementations:


func Any[T any](ss []T, test func(T) bool) bool {
	for _, s := range ss {
		if test(s) {
			return true
		}
	}
	return false
}

func None[T any](ss []T, test func(T) bool) bool {
	for _, s := range ss {
		if test(s) {
			return false
		}
	}
	return true
}

@bobg
Copy link
Owner

bobg commented Feb 21, 2023

Thank you for this suggestion.

As presented here, the functions seem too special-purpose to be in keeping with the other features of this module. A more general approach would allow you to, say, find the index of the first value that passes the test. It could return -1 if no such value is found. This allows the trivial implementation of Any and None and plenty of other functions besides.

func Any[T any](s []T, test func(T) bool) bool {
  return indexOf(s, test) >= 0
}

func None[T any](s []T, test func(T) bool) bool {
  return !Any(s, test)
}

func All[T any](s []T, test func(T) bool) bool {
  notTest := func(val T) bool { return !test(val) }
  return !Any(s, notTest)
}

As it happens, I am presently updating the go-generics module to align with the planned inclusion, in Go 1.21, of new slices and maps packages in the standard library. See golang/go#57433 and golang/go#57436. The idea is for my slices and maps to be drop-in replacements for the stdlib versions, with enhancements. And the stdlib slices package will include IndexFunc, which behaves in exactly the way I illustrated above with indexOf.

Sound OK?

@bobg
Copy link
Owner

bobg commented Feb 21, 2023

(In fact, slices.ContainsFunc is exactly your Any.)

@cloudshiftchris
Copy link
Author

Sounds good. Thanks for sharing the broader context.

@bobg bobg closed this as completed Feb 21, 2023
@bobg bobg mentioned this issue Aug 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants