Skip to content

Instantly share code, notes, and snippets.

@janderit janderit/Union.cs
Created Oct 25, 2015

Embed
What would you like to do?
C# discriminated union type
// adapted from : http://stackoverflow.com/questions/3151702/discriminated-union-in-c-sharp by Juliet
public abstract class Union<TA, TB, TC>
{
public static Case1 Create(TA x) { return new Case1(x);}
public static Case2 Create(TB x) { return new Case2(x);}
public static Case3 Create(TC x) { return new Case3(x);}
public abstract T Match<T>(Func<TA, T> f, Func<TB, T> g, Func<TC, T> h);
private Union() { }
public sealed class Case1 : Union<TA, TB, TC>
{
public readonly TA Item;
public Case1(TA item) { Item = item; }
public override T Match<T>(Func<TA, T> f, Func<TB, T> g, Func<TC, T> h)
{
return f(Item);
}
}
public sealed class Case2 : Union<TA, TB, TC>
{
public readonly TB Item;
public Case2(TB item) { Item = item; }
public override T Match<T>(Func<TA, T> f, Func<TB, T> g, Func<TC, T> h)
{
return g(Item);
}
}
public sealed class Case3 : Union<TA, TB, TC>
{
public readonly TC Item;
public Case3(TC item) { Item = item; }
public override T Match<T>(Func<TA, T> f, Func<TB, T> g, Func<TC, T> h)
{
return h(Item);
}
}
}
// adapted from : http://stackoverflow.com/questions/3151702/discriminated-union-in-c-sharp by Juliet
public abstract class Union<TA, TB>
{
public static Case1 Create(TA x) { return new Case1(x);}
public static Case2 Create(TB x) { return new Case2(x);}
public abstract void Match(Action<TA> f, Action<TB> g);
public abstract T Match<T>(Func<TA, T> f, Func<TB, T> g);
private Union() { }
public sealed class Case1 : Union<TA, TB>
{
public readonly TA Item;
public Case1(TA item) { Item = item; }
public override void Match(Action<TA> f, Action<TB> g)
{
f(Item);
}
public override T Match<T>(Func<TA, T> f, Func<TB, T> g)
{
return f(Item);
}
}
public sealed class Case2 : Union<TA, TB>
{
public readonly TB Item;
public Case2(TB item) { Item = item; }
public override void Match(Action<TA> f, Action<TB> g)
{
g(Item);
}
public override T Match<T>(Func<TA, T> f, Func<TB, T> g)
{
return g(Item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.