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

IsNoneOr(predicate) #61

Open
julienroubieu opened this issue Dec 14, 2018 · 2 comments
Open

IsNoneOr(predicate) #61

julienroubieu opened this issue Dec 14, 2018 · 2 comments

Comments

@julienroubieu
Copy link

Hi Nils!

I couldn't find a method to check if an Option is empty or satisfies a given predicate.
I'm looking for an equivalent for scala's forall behaviour on Option.

I'm seeing two ways of getting this currently:

if (!opt.HasValue || opt.Exists(Predicate)) { ... }
if (opt.Map(Predicate).ValueOr(true)) { ... }

Is there some easier way that I missed?

If not, would you consider adding something like if (opt.IsEmptyOr(Predicate)), which would be more readable IMO. I might work on a PR if you are willing to accept it.

@nlkl
Copy link
Owner

nlkl commented Dec 16, 2018

Hi!

Currently, I think the most concise you can get would be something like:

if (!option.Exists(value => !Predicate(value)))
{
}

However, I agree that this is a bit more obfuscated than necessary. I have run into this a few times myself, and considered adding it to Optional more than once, but truth be told I have postponed adding it as I haven't been able to find a name for the operation that I really liked.

Something like ForAll (or All) is probably my current preference, as it fits well with Exists and aligns with the corresponding name in F# - but it does seem a little off for something that can never have more than a single element.

On the other hand IsEmptyOr is a very descriptive name, but unfortunately doesn't go as well with Exists (which, to be honest, might be more of fault with the Exists name itself).

If you have any thoughts on the matter I would love to hear it - otherwise I will give it a bit of thought, and probably include the operation in Optional 4.1.0 which will be released in the not too distant future.

/ Nils

@julienroubieu
Copy link
Author

Hi Nils, it's great that you're planning to add this method.

I share your concerns about both possible names, there is no perfect one that is both immediately understandable by newcomers and coherent with other languages and libs.

To me, "doesn't fit Exists well" is not really an issue. Being easily used and producing understandable code should take precedence.

I don't know how you feel about defining an alias, but it would allow the lib users to choose whichever they find best for each situation.

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