Skip to content

Instantly share code, notes, and snippets.

@horsdal
Last active August 29, 2015 13:56
Show Gist options
  • Save horsdal/9102124 to your computer and use it in GitHub Desktop.
Save horsdal/9102124 to your computer and use it in GitHub Desktop.
public class Option<T> : IEnumerable<T>
{
public T Value { get; private set; }
public bool IsSome { get { return this != None; } }
public static readonly Option<T> None = new Option<T>(default(T));
public static Option<T> Some(T value)
{
return new Option<T>(value);
}
private Option(T value)
{
Value = value;
}
public IEnumerator<T> GetEnumerator()
{
if (IsSome)
yield return Value;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public TRes Match<TRes>(Func<T, TRes> some, Func<TRes> none)
{
if (IsSome)
return some.Invoke(Value);
else
return none.Invoke();
}
public void Match(Action<T> some, Action none)
{
if (IsSome)
some.Invoke(Value);
else
none.Invoke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment