Skip to content

Instantly share code, notes, and snippets.

@dewf
Last active March 17, 2020 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dewf/dadc0f2775b40b65a3ebf7458d3c2c79 to your computer and use it in GitHub Desktop.
Save dewf/dadc0f2775b40b65a3ebf7458d3c2c79 to your computer and use it in GitHub Desktop.
inheritance-based pattern matching in D
import std.stdio;
class MySumType {
// any shared fields / abstract methods go here
abstract void match(Matcher m);
}
class Matcher {
void case_(IntValue v) { else_(v); }
void case_(FloatValue v) { else_(v); }
void case_(StringValue v) { else_(v); }
void case_(MultiValues v) { else_(v); }
void else_(MySumType v) {}
}
class IntValue : MySumType {
int value;
this(int value) { this.value = value; }
override void match(Matcher m) { m.case_(this); }
}
class FloatValue : MySumType {
float value;
this(float value) { this.value = value; }
override void match(Matcher m) { m.case_(this); }
}
class StringValue : MySumType {
string value;
this(string value) { this.value = value; }
override void match(Matcher m) { m.case_(this); }
}
class MultiValues : MySumType {
int a, b;
string c;
this(int a, int b, string c) { this.a = a; this.b = b; this.c = c; }
override void match(Matcher m) { m.case_(this); }
}
void main()
{
MySumType[] values = [
new IntValue(101),
new FloatValue(300.1),
new StringValue("why hello there!"),
new MultiValues(1001, 2002, "three thousand three")
];
foreach (v; values) {
writefln("\nfor object [%s]:", v);
int retval;
scope m = new class Matcher {
override void case_(IntValue v) {
writefln(" - we got an int value: %d", v.value);
retval = 100;
}
override void case_(MultiValues v) {
writefln(" - we got multi values: %d, %d, '%s'", v.a, v.b, v.c);
retval = 999;
}
override void else_(MySumType v) {
writefln(" - else case: [%s]", v);
}
};
v.match(m);
writefln("* retval was: %d", retval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment