Skip to content

Instantly share code, notes, and snippets.

@kseo
Created January 19, 2015 07:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kseo/a8313ef4527fcd561b38 to your computer and use it in GitHub Desktop.
Save kseo/a8313ef4527fcd561b38 to your computer and use it in GitHub Desktop.
Step by step implementation of Option type in C#
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