Created
August 21, 2009 04:28
-
-
Save dvdsgl/171666 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Data | |
{ | |
public struct Maybe<T> where T : class | |
{ | |
public static implicit operator Maybe<T> (T value) | |
{ | |
return new Maybe<T> (value); | |
} | |
T value; | |
Maybe (T value) | |
{ | |
this.value = value; | |
} | |
public bool IsNull { get { return value == null; } } | |
public bool IsNotNull { get { return value != null; } } | |
public T Value { | |
get { | |
if (IsNull) throw new NullReferenceException (); | |
return value; | |
} | |
} | |
public T Out () | |
{ | |
if (IsNull) throw new NullReferenceException (); | |
return value; | |
} | |
public T Out (T alt) | |
{ | |
if (alt == null) | |
throw new NullReferenceException ("alternative value cannot be null"); | |
return IsNotNull ? value : alt; | |
} | |
public R Out<R> (R alt, Func<T, R> f) where R : class | |
{ | |
if (alt == null) | |
throw new NullReferenceException ("alternative value cannot be null"); | |
return IsNotNull ? f (value) : alt; | |
} | |
public Maybe<R> Bind<R> (Func<T, Maybe<R>> f) where R : class | |
{ | |
return IsNotNull ? f (value) : null; | |
} | |
public Maybe<R> Map<R> (Func<T, R> f) where R : class | |
{ | |
return Bind (t => new Maybe<R> (f (t))); | |
} | |
public override string ToString() | |
{ | |
return Out ("(null)", t => t.ToString ()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment