Optional icon indicating copy to clipboard operation
Optional copied to clipboard

IsNoneOr(predicate)

Open julienroubieu opened this issue 5 years ago • 2 comments

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.

julienroubieu avatar Dec 14 '18 19:12 julienroubieu

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

nlkl avatar Dec 16 '18 16:12 nlkl

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.

julienroubieu avatar Dec 17 '18 15:12 julienroubieu