Created
March 23, 2021 10:06
-
-
Save mike-kilo/2613a417bfd461e349849ce7b7441cd8 to your computer and use it in GitHub Desktop.
Either - like in F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Helpers | |
{ | |
public class Either<TL, TR> | |
{ | |
private readonly TL left; | |
private readonly TR right; | |
private readonly bool isLeft; | |
public Either(TL left) | |
{ | |
this.left = left; | |
this.isLeft = true; | |
} | |
public Either(TR right) | |
{ | |
this.right = right; | |
this.isLeft = false; | |
} | |
public T Match<T>(Func<TL, T> leftFunc, Func<TR, T> rightFunc) => this.isLeft ? leftFunc(this.left) : rightFunc(this.right); | |
public Either<TL, TR> InvokeOn<T>(T param, Func<TL, T, TL> leftFunc, Func<TR, T, TR> rightFunc) => this.isLeft ? new Either<TL, TR>(leftFunc(this.left, param)) : new Either<TL, TR>(rightFunc(this.right, param)); | |
public Either<TL, TR> InvokeOn<T>(T[] param, Func<TL, T[], TL> leftFunc, Func<TR, T[], TR> rightFunc) => this.isLeft ? new Either<TL, TR>(leftFunc(this.left, param)) : new Either<TL, TR>(rightFunc(this.right, param)); | |
public bool IsOfType(Type t) => this.isLeft && typeof(TL).Equals(t) || !this.isLeft && typeof(TR).Equals(t); | |
public static implicit operator Either<TL, TR>(TL left) => new Either<TL, TR>(left); | |
public static implicit operator Either<TL, TR>(TR right) => new Either<TL, TR>(right); | |
public static implicit operator TL(Either<TL, TR> e) | |
{ | |
if (e.isLeft == true) return e.left; | |
throw new InvalidCastException($"This object is not of type {typeof(TL).ToString()}"); | |
} | |
public static implicit operator TR(Either<TL, TR> e) | |
{ | |
if (e.isLeft == false) return e.right; | |
throw new InvalidCastException($"This object is not of type {typeof(TR).ToString()}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from https://github.com/mikhailshilkov/mikhailio-samples/blob/1456e4ad61db1d0ae633f9262218aa09a9fda645/Either%7BTL,TR%7D.cs and extended with couple of new methods (casting, method invoke, etc.)