Created
December 16, 2019 23:22
-
-
Save afifmohammed/429af9ceac8b4078c4664a8cfb921563 to your computer and use it in GitHub Desktop.
Discriminated unions in C#
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; | |
namespace Juliet | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Union3<int, char, string>[] unions = new Union3<int,char,string>[] | |
{ | |
new Union3<int, char, string>(5), | |
new Union3<int, char, string>('x'), | |
new Union3<int, char, string>("Juliet") | |
}; | |
foreach (Union3<int, char, string> union in unions) | |
{ | |
string value = union.Match( | |
num => num.ToString(), | |
character => new string(new char[] { character }), | |
word => word); | |
Console.WriteLine("Matched union with value '{0}'", value); | |
} | |
Console.ReadLine(); | |
} | |
} | |
public sealed class Union3<A, B, C> | |
{ | |
readonly A Item1; | |
readonly B Item2; | |
readonly C Item3; | |
int tag; | |
public Union3(A item) { Item1 = item; tag = 0; } | |
public Union3(B item) { Item2 = item; tag = 1; } | |
public Union3(C item) { Item3 = item; tag = 2; } | |
public T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h) | |
{ | |
switch (tag) | |
{ | |
case 0: return f(Item1); | |
case 1: return g(Item2); | |
case 2: return h(Item3); | |
default: throw new Exception("Unrecognized tag value: " + tag); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied here for quick look up from
https://stackoverflow.com/questions/3151702/discriminated-union-in-c-sharp#3199453