Created
April 7, 2020 16:23
-
-
Save bymyslf/d5407bc7254f18cc44fa9b2f72be9f7f to your computer and use it in GitHub Desktop.
C# Either Monad
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; | |
public class Either<TLeft, TRight> | |
{ | |
private readonly TLeft left; | |
private readonly TRight right; | |
private readonly bool isLeft; | |
public Either(TLeft left) | |
{ | |
this.left = left; | |
this.isLeft = true; | |
} | |
public Either(TRight right) | |
{ | |
this.right = right; | |
this.isLeft = false; | |
} | |
public T Match<T>(Func<TLeft, T> leftFunc, Func<TRight, T> rightFunc) | |
=> this.isLeft ? leftFunc(this.left) : rightFunc(this.right); | |
public static implicit operator Either<TLeft, TRight>(TLeft left) | |
=> new Either<TLeft, TRight>(left); | |
public static implicit operator Either<TLeft, TRight>(TRight right) | |
=> new Either<TLeft, TRight>(right); | |
public static explicit operator TLeft(Either<TLeft, TRight> either) | |
=> either.left; | |
public static explicit operator TRight(Either<TLeft, TRight> either) | |
=> either.right; | |
} | |
public static class Either | |
{ | |
public static Either<TLeft, TRight> Left<TLeft, TRight>(TLeft value) | |
=> new Either<TLeft, TRight>(value); | |
public static Either<TLeft, TRight> Right<TLeft, TRight>(TRight value) | |
=> new Either<TLeft, TRight>(value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment