Created
January 19, 2015 07:00
-
-
Save kseo/a8313ef4527fcd561b38 to your computer and use it in GitHub Desktop.
Step by step implementation of Option type in C#
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 abstract class Option<T> | |
{ | |
public abstract T Value { get; } | |
public abstract bool IsSome { get; } | |
public abstract bool IsNone { get; } | |
public abstract Option<TResult> Map<TResult>(Func<T, TResult> func); | |
public abstract TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc); | |
} | |
public sealed class None<T> : Option<T> | |
{ | |
public None() | |
{ | |
} | |
public override T Value | |
{ | |
get { throw new System.NotSupportedException("There is no value"); } | |
} | |
public override bool IsSome { get { return false; } } | |
public override bool IsNone { get { return true; } } | |
public override Option<TResult> Map<TResult>(Func<T, TResult> func) | |
{ | |
return new None<TResult>(); | |
} | |
public override TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc) | |
{ | |
return noneFunc(); | |
} | |
} | |
public sealed class Some<T> : Option<T> | |
{ | |
private T value; | |
public Some(T value) | |
{ | |
if (value == null) | |
{ | |
throw new System.ArgumentNullException("value", "Some value was null, use None instead"); | |
} | |
this.value = value; | |
} | |
public override T Value { get { return value; } } | |
public override bool IsSome { get { return true; } } | |
public override bool IsNone { get { return false; } } | |
public override Option<TResult> Map<TResult>(Func<T, TResult> func) | |
{ | |
return new Some<TResult>(func(value)); | |
} | |
public override TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc) | |
{ | |
return someFunc(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment