Created
December 21, 2016 02:21
-
-
Save cameronpresley/7bbdbdee412ae9113aa2c451a836191d to your computer and use it in GitHub Desktop.
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
using System; | |
namespace Option | |
{ | |
public class Option<T> | |
{ | |
private readonly T _value; | |
private readonly bool _hasValue; | |
private Option(T value, bool hasValue) | |
{ | |
_value = value; | |
_hasValue = hasValue; | |
} | |
public static Option<T> None() | |
{ | |
return new Option<T>(default(T), false); | |
} | |
public static Option<T> Some(T value) | |
{ | |
if (value == null) return None(); | |
return new Option<T>(value, true); | |
} | |
public void PerformAction(Action<T> ifSome, Action ifNone) | |
{ | |
if (_hasValue) | |
ifSome(_value); | |
else | |
ifNone(); | |
} | |
public U Map<U>(Func<T, U> ifSome, Func<U> ifNone) | |
{ | |
return _hasValue ? ifSome(_value) : ifNone(); | |
} | |
} | |
} | |
// Example Usage | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = Divide(4, 0); | |
result.PerformAction(Console.WriteLine, () => Console.WriteLine("Failed to parse")); | |
result = Divide(4, 2); | |
result.PerformAction(Console.WriteLine, () => Console.WriteLine("Failed to parse.")); | |
var mappedResult = result.Map(x => x, () => 0); | |
Console.WriteLine("Result is " + mappedResult); | |
} | |
private static Option<int> Divide(int a, int b) | |
{ | |
return b == 0 ? Option<int>.None() : Option<int>.Some(a/b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment