Skip to content

Instantly share code, notes, and snippets.

@lambdaknight
Created May 9, 2013 16:52
Show Gist options
  • Select an option

  • Save lambdaknight/5548767 to your computer and use it in GitHub Desktop.

Select an option

Save lambdaknight/5548767 to your computer and use it in GitHub Desktop.

Revisions

  1. lambdaknight created this gist May 9, 2013.
    123 changes: 123 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,123 @@
    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
    }