Skip to content

Instantly share code, notes, and snippets.

@lambdaknight
Created May 9, 2013 16:52
Show Gist options
  • Save lambdaknight/5548767 to your computer and use it in GitHub Desktop.
Save lambdaknight/5548767 to your computer and use it in GitHub Desktop.
Maybe in C#?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public sealed class Maybe<T>
{
private readonly bool _hasValue;
private readonly T _value;
#region Constructors
public Maybe(T value)
{
_value = value;
_hasValue = true;
}
private Maybe()
{
}
#endregion
#region Methods
public bool IsJust
{
get
{
return _hasValue;
}
}
public bool IsNothing
{
get
{
return !_hasValue;
}
}
public static implicit operator T(Maybe<T> maybe)
{
return maybe.FromJust();
}
public static implicit operator Maybe<T>(T val)
{
return new Maybe<T>(val);
}
public T FromJust()
{
if(IsNothing)
{
throw new ArgumentException(string.Format("Cannot convert Nothing to {0}.", typeof(T).Name));
}
return _value;
}
public T FromMaybe(T def)
{
if(IsJust)
{
return FromJust();
}
else
{
return def;
}
}
/**
* Override to ToString
**/
public override string ToString()
{
if(IsNothing)
{
return "Nothing";
}
else
{
return string.Format("Just({0})", FromJust());
}
}
#endregion
#region Static Members
/**
* Static Members. This only contains the special "Nothing" value.
**/
public static readonly Maybe<T> Nothing = new Maybe<T>();
#endregion
#region Static Methods
/**
* Static Methods.
* Static versions of FromMaybe and FromJust
**/
public static T FromMaybe(Maybe<T> maybe, T def)
{
if(maybe.IsJust)
{
return maybe._value;
}
else
{
return def;
}
}
public static T FromJust(Maybe<T> maybe)
{
if(maybe.IsNothing)
{
throw new ArgumentException("Argument to FromJust cannot be Nothing.");
}
else
{
return maybe._value;
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment