Skip to content

Instantly share code, notes, and snippets.

@noblethrasher
Created June 18, 2018 21:23
Show Gist options
  • Save noblethrasher/2d0e99f86b9853c646f3fa91c59b2223 to your computer and use it in GitHub Desktop.
Save noblethrasher/2d0e99f86b9853c646f3fa91c59b2223 to your computer and use it in GitHub Desktop.
public abstract class Maybe<T>
{
public abstract T Value { get; }
public virtual string Failure => null;
public Maybe<V> SelectMany<U, V>(Func<T, Maybe<U>> f, Func<T, U, V> g)
{
var that = f(this.Value);
if (that.Failure != null)
return new Failed<V>(that.Failure);
return new Success<V>(g(this.Value, that.Value));
}
public sealed class Success<U> : Maybe<U>
{
readonly U value;
public override U Value => value;
public Success(U value) => this.value = value;
}
public sealed class Failed<U> : Maybe<U>
{
readonly string failure;
public override string Failure { get; }
public override U Value => throw new InvalidOperationException();
public Failed(string s) => this.failure = s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment