Skip to content

Instantly share code, notes, and snippets.

@bymyslf
Created April 7, 2020 16:23
Show Gist options
  • Save bymyslf/d5407bc7254f18cc44fa9b2f72be9f7f to your computer and use it in GitHub Desktop.
Save bymyslf/d5407bc7254f18cc44fa9b2f72be9f7f to your computer and use it in GitHub Desktop.
C# Either Monad
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