Skip to content

Instantly share code, notes, and snippets.

@dvdsgl
Created August 21, 2009 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvdsgl/171666 to your computer and use it in GitHub Desktop.
Save dvdsgl/171666 to your computer and use it in GitHub Desktop.
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