Last active
January 27, 2017 14:05
-
-
Save alphaKAI/e599cdf69093ea7051bbdbd1c475c83f to your computer and use it in GitHub Desktop.
Binary Tree with Pattern matching in D
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
import std.algorithm, | |
std.traits, | |
std.format, | |
std.range, | |
std.array; | |
bool instanceof(alias Type, alias Variable)() { | |
return (cast(Type)Variable) !is null; | |
} | |
string caseof(alias instance, Type, Variables...)() { | |
string code = | |
q{assert (instanceof!(%s, %s), | |
"Type doesn't match, caseof expects that the variable `instance` is typed as %s, but given `instance` is not an instance of %s");} | |
.format(Type.stringof, instance.stringof, Type.stringof, Type.stringof); | |
string[] vtypes; | |
string[] vnames_type; | |
string[] vnames_req; | |
foreach (vtype; Fields!Type) { | |
vtypes ~= vtype.stringof; | |
} | |
foreach (vname; FieldNameTuple!Type) { | |
vnames_type ~= vname; | |
} | |
foreach (variable; Variables) { | |
vnames_req ~= variable; | |
} | |
foreach (vtype, vname_type, vname_req; zip(vtypes, vnames_type, vnames_req)) { | |
code ~= "%s %s = (cast(%s)%s).%s;".format(vtype, vname_req, Type.stringof, instance.stringof, vname_type); | |
} | |
return code; | |
} | |
/* | |
data Node = Leaf Int | |
| Branch Node Node | |
*/ | |
interface Node {} | |
class Leaf : Node { int a; this (int a) { this.a = a; } } | |
class Branch : Node { Node l, r; this (Node l, Node r) { this.l = l; this.r = r; }} | |
// Helper functions | |
Leaf leaf(int a) { return new Leaf(a); } | |
Branch branch(Node l, Node r) { return new Branch(l, r); } | |
/* | |
returns depth of the tree | |
depth :: Node -> Int | |
depth tree = case tree of | |
Leaf _ -> 1 | |
Branch a b -> 1 + max (depth a) (depth b) | |
*/ | |
size_t depth(Node tree) { | |
if (instanceof!(Leaf, tree)) { | |
return 1; | |
} else if (instanceof!(Branch, tree)) { | |
mixin(caseof!(tree, Branch, "a", "b")); | |
return 1 + max(a.depth, b.depth); | |
} else { | |
throw new Error("Unknown tree was given"); | |
} | |
} | |
import std.stdio; | |
void main() { | |
Node tree = branch(branch(branch(leaf(1), leaf(2)), leaf(3)), leaf(4)); | |
writeln(tree.depth); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment