Structural Pattern Matching in Java
apocalisp.wordpress.com
apocalisp.wordpress.com
class Tree {
public:
virtual int depth() = 0;
};
class Empty: public Tree {
public:
virtual int depth() { return 0; }
};
class Leaf: public Tree {
int n;
public:
virtual int depth() { return 1; }
};
class Node: public Tree {
Tree* l;
Tree* r;
public:
virtual int depth()
{
return 1 + max(l->depth(), r->depth());
}
};
Since I've never programmed in a language with structural pattern matching, I welcome others to compare my solution to what was presented. Clearly, structural pattern matching requires less code. Also, I've never actually read the Design Patterns book, but I think what I have above is different from the Interpreter and Visitor pattern he described in the article - for one, I don't have any mutation. But, again, please correct me if I'm wrong.