Skip to content

Instantly share code, notes, and snippets.

@arnihermann
Last active December 14, 2015 13:08
Show Gist options
  • Save arnihermann/5091145 to your computer and use it in GitHub Desktop.
Save arnihermann/5091145 to your computer and use it in GitHub Desktop.
Either.cs
public abstract class Either<A, B>
{
private Either() { }
abstract public T Fold<T>(Func<A, T> leftFold, Func<B, T> rightFold);
abstract public bool HasError { get; }
public sealed class Left<A, B> : Either<A, B>
{
public readonly A error;
public Left(A error) {
this.error = error;
}
public override T Fold<T>(Func<A, T> leftFold, Func<B, T> rightFold)
{
return leftFold(error);
}
public override bool HasError
{
get { return true; }
}
}
public sealed class Right<A, B> : Either<A, B>
{
public readonly B value;
public Right(B value)
{
this.value = value;
}
public override T Fold<T>(Func<A, T> leftFold, Func<B, T> rightFold)
{
return rightFold(value);
}
public override bool HasError
{
get { return false; }
}
}
public static Either<A, B> left(A error)
{
return new Left<A, B>(error);
}
public static Either<A, B> right(B value)
{
return new Right<A, B>(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment