Last active
January 17, 2017 14:01
-
-
Save einarwh/77445006d6f72c16d3d441a627c0bd5b to your computer and use it in GitHub Desktop.
Mayhaps value, mayhaps not.
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
public abstract class Mayhaps<T> | |
{ | |
private Mayhaps() {} | |
public abstract bool HasValue { get; } | |
public abstract T Value { get; } | |
public abstract Mayhaps<TR> Map<TR>(Func<T, TR> f); | |
private class MayhapsValue : Mayhaps<T> | |
{ | |
private readonly T _value; | |
public MayhapsValue(T value) | |
{ | |
if (value == null) { | |
throw new ArgumentNullException("Begone, null!"); | |
} | |
_value = value; | |
} | |
public override bool HasValue | |
{ | |
get { return true; } | |
} | |
public override T Value | |
{ | |
get { return _value; } | |
} | |
public override Mayhaps<TR> Map<TR>(Func<T, TR> f) | |
{ | |
return Mayhaps<TR>.Indeed(f(_value)); | |
} | |
} | |
private class MayhapsNothing : Mayhaps<T> | |
{ | |
public override bool HasValue | |
{ | |
get { return false; } | |
} | |
public override T Value | |
{ get { throw new InvalidOperationException("Nothing here."); } } | |
public override Mayhaps<TR> Map<TR>(Func<T, TR> f) | |
{ | |
return Mayhaps<TR>.Nothing; | |
} | |
} | |
private static MayhapsNothing _nothing = new MayhapsNothing(); | |
public static Mayhaps<T> Indeed(T value) | |
{ | |
return new MayhapsValue(value); | |
} | |
public static Mayhaps<T> Nothing | |
{ | |
get { return _nothing; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment