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: cmp: add OrFunc #66986

Open
laher opened this issue Apr 23, 2024 · 2 comments
Open

proposal: cmp: add OrFunc #66986

laher opened this issue Apr 23, 2024 · 2 comments
Labels
Milestone

Comments

@laher
Copy link

laher commented Apr 23, 2024

Proposal Details

Related to #60204 - I find cmp.Or very useful, although I would appreciate a variant which does not 'execute' the inputs to subsequent parameters.

I propose a variant of this function, which itself takes in a variable number of functions, and executes each until one of them returns a non-zero result.

The motivation for this is to provide behaviour similar to connect() || die('ohnoes') in Perl, Ruby, etc. So, each parameter is like a 'fallback' of the previous parameter. It should only be executed if the previous parameter(s) returned zero.

// OrFunc returns the the return-value of the first argument (a function), that is not equal to the zero value.
// If no argument is non-zero, it returns the zero value.
// OrFunc is inspired by Or and Perl's`||` operator
func OrFunc[T comparable, F func() T](funcs ...F) T {
	var zero T
	for _, f := range funcs {
		t := f()
		if t != zero {
			return t
		}
	}
	return zero
}

See here for a working example: https://go.dev/play/p/GYr6qeT7pDg

Thanks!

@laher laher added the Proposal label Apr 23, 2024
@adonovan
Copy link
Member

Regardless of whether we add that function to the library, it should not be called And, as it is not the dual of Or due to the lazy or "short-circuit" behavior. An And that is the strict dual seems like a reasonable function, so we shouldn't foreclose adding it later, even if there seems to be little need.

How often does this need really arise? The resulting code isn't especially pretty, compared to, say, a single function containing an if-else chain of return statements.

@earthboundkid
Copy link
Contributor

I don't think this makes sense in a world without short function literals (#21498). Even with short function literals, it's not clear that this is better than an if-else chain.

@ianlancetaylor ianlancetaylor changed the title cmp: add OrFunc proposal: cmp: add OrFunc Apr 23, 2024
@gopherbot gopherbot added this to the Proposal milestone Apr 23, 2024
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