Skip to content

Instantly share code, notes, and snippets.

@dadhi
Created January 24, 2018 23:52
Show Gist options
  • Save dadhi/9ca6a8b1477301dc1398ee815bf594a3 to your computer and use it in GitHub Desktop.
Save dadhi/9ca6a8b1477301dc1398ee815bf594a3 to your computer and use it in GitHub Desktop.
Struct Either with renaming in C#
using System;
public class C {
public Result<int>.Or M() =>
Result<int>.Left(2);
}
public class Result<T> : Either<T, Exception> {}
public class Either<L, R>
{
// todo: + implicit ops to Or
public static Or Left(L l) => new Or(l);
public static Or Right(R r) => new Or(r);
public struct Or
{
L _l; R _r; byte _state;
public bool IsLeft => _state == 0
? throw new InvalidOperationException("Not initialized " + GetType())
: _state == 1;
public Or(L l) { _l = l; _r = default; _state = 1; }
public Or(R r) { _l = default; _r = r; _state = 2; }
public T Match<T>(Func<L,T> left, Func<R,T> right) =>
IsLeft ? left(_l) : right(_r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment