Skip to content

Instantly share code, notes, and snippets.

@otf
Created May 13, 2013 08:51
Show Gist options
  • Save otf/5567013 to your computer and use it in GitHub Desktop.
Save otf/5567013 to your computer and use it in GitHub Desktop.
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