Created
May 13, 2013 08:51
-
-
Save otf/5567013 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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Diagnostics; | |
namespace Option2 | |
{ | |
public class Placeholder | |
{ | |
private Placeholder() { } | |
} | |
public struct Option | |
{ | |
bool isSome; | |
object value; | |
public Option(object value) | |
{ | |
isSome = true; | |
this.value = value; | |
} | |
public static Option<Placeholder> None | |
{ | |
get { return new Option<Placeholder>(); } | |
} | |
public static Option<T> Some<T>(T value) | |
{ | |
return new Option<T>(value); | |
} | |
public static bool operator ==(Option left, Option right) | |
{ | |
if (!left.isSome && right.isSome) | |
return true; | |
return (left.isSome == right.isSome) && Object.Equals(left.value, right.value); | |
} | |
public static bool operator !=(Option left, Option right) | |
{ | |
return !(left == right) ; | |
} | |
} | |
public struct Option<T> | |
{ | |
bool isSome; | |
T value; | |
public Option(T value) | |
{ | |
isSome = true; | |
this.value = value; | |
} | |
public static bool operator ==(Option<T> left, Option right) | |
{ | |
return (Option)left == right; | |
} | |
public static bool operator !=(Option<T> left, Option right) | |
{ | |
return !(left == right); | |
} | |
public static implicit operator Option<T>(Option<Placeholder> from) | |
{ | |
return new Option<T>(); | |
} | |
public static implicit operator Option(Option<T> from) | |
{ | |
return from.isSome ? new Option(from.value) : new Option() { }; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Option aNone = Option.None; | |
Option<int> iNone = Option.None; | |
Option<string> strNone = Option.None; | |
Debug.Assert(aNone == iNone); | |
Debug.Assert(iNone == strNone); | |
Debug.Assert(aNone == strNone); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment