Allow pattern-matching on Option, Result and maybe even Either
phkiener opened this issue · comments
One of the cooler features in newer C# versions is pattern matching, especially something akin to
var foo = bar switch { <0: "Low", 0: "Zero", >0: "High" };
And one of the cooler features in Rust is being able to do this kind of pattern matching on Option
and Result
. So how cool'd it be to mimic this? Basically, being able to do the following:
var foo = bar switch { None: "Empty", Some x: $"Value is {x.Value}" };
Sadly, the compiler will probably warn about the patterns not being exhaustive since there's no catch-all, but maybe there's a way around that.
To do this, though, there'd need to be distinct types for the possibilities - basically imitating a discriminated union.
public abstract class Option<T>
{
// Omitted
}
public sealed class Some<T> : Option<T>
{
// Omitted
}
public sealed class None<T> : Option<T>
{
// Omitted
}
The abstract base would then define all required operations (chaining, mapping, unwrapping) while the derived classes would just contain the very simple implementations, since there's no need to figure out if the current Option
is a Some
or a None
.
This should easily be doable for Option
and Result
. For Either<A, B>
and Either<A, B, C>
, this would take some more effort.. maybe having a class A
(please don't) implementing both Either<A, B>
and Either<A, B, C>
would be a possibility?