Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Created June 5, 2012 18:54
Show Gist options
  • Save bkyrlach/2876941 to your computer and use it in GitHub Desktop.
Save bkyrlach/2876941 to your computer and use it in GitHub Desktop.
Replicating Scala Option
//Usage
Option<String> someString = Option<String>.Some("Hi");
Option<String> noString = Option<String>.None();
Console.WriteLine(someString.Select(x => x.Length).GetOrElse(-1));
Console.WriteLine(noString.Select(x => x.Length).GetOrElse(-1));
//Definition
abstract class Option<T>
{
public abstract T Get();
public abstract bool IsEmpty();
public static Some<T> Some(T t)
{
return new Some<T>(t);
}
public static None<T> None()
{
return new None<T>();
}
public Option<B> Select<B>(Func<T, B> selector)
{
if (IsEmpty())
{
return new None<B>();
}
else
{
return new Some<B>(selector(Get()));
}
}
public Option<B> SelectMany<B>(Func<T, Option<B>> selector)
{
if (IsEmpty())
{
return new None<B>();
}
else
{
return selector(Get());
}
}
public T GetOrElse(T defaultValue)
{
if (IsEmpty())
{
return defaultValue;
}
else
{
return Get();
}
}
class None<T> : Option<T>
{
public None()
{
}
public override T Get()
{
throw new NoValueException();
}
public override bool IsEmpty()
{
return true;
}
}
class Some<T> : Option<T>
{
private T val;
public Some(T t)
{
this.val = t;
}
public override T Get()
{
return val;
}
public override bool IsEmpty()
{
return false;
}
}
class NoValueException : Exception
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment