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

Allow pattern-matching on Option, Result and maybe even Either #28

Open
phkiener opened this issue Aug 21, 2022 · 0 comments
Open

Allow pattern-matching on Option, Result and maybe even Either #28

phkiener opened this issue Aug 21, 2022 · 0 comments

Comments

@phkiener
Copy link
Collaborator

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant