Created
June 5, 2012 18:54
-
-
Save bkyrlach/2876941 to your computer and use it in GitHub Desktop.
Replicating Scala Option
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
//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