DigitecGalaxus / DigitecGalaxus/Galaxus.Functional

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

Open
#28 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
41
Forks
13
PR merge metrics
No merged PRs in 30d

Description

One of the cooler features in newer C# versions is pattern matching, especially something akin to
```csharp
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:

```csharp
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.

```csharp
public abstract class Option
{
// Omitted
}

public sealed class Some : Option
{
// Omitted
}

public sealed class None : Option
{
// 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` and `Either`, this would take some more effort.. maybe having a class `A` (please don't) implementing both `Either` and `Either` would be a possibility?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.