Pattern match in Java
Java に無名関数と関数型が導入されるらしい。が、無名クラスあるからいいじゃん、どうせ Eclipse が自動で入力してくれるよ、そんなことよりパターンマッチと Variant 入れてよ、木が書けん、Visitor とかマジ鬱、というはなしがありました。
昨日の夜思いついて、今実装してみたら、ちゃんと動いた。動いたっていっても、あれなんですが。
public class Variant { public static void main(String[] args) { Node n = new Node("n1", new Base[]{ new Leaf("l1"), new Node("n2", new Base[]{ new Leaf("l2"), new Leaf("l3") })}); f(n, 0); } private static void f(Base base, int depth) { for (int i = 0; i < depth; i++) System.out.print(' '); try { throw base; } catch(Node n) { System.out.println("node:" + n.data); for (int i = 0; i < n.children.length; i++) { f(n.children[i], depth + 1); } } catch(Leaf l) { System.out.println("leaf: " + l.data); } catch(Base b) { System.out.println("error"); } } } abstract class Base extends Exception { } class Node extends Base { public Node(String d, Base[] ch) { data = d; children = ch; } public String data; public Base[] children; } class Leaf extends Base { public Leaf(String d) { data = d; } public String data; }
実行結果
node:n1 leaf: l1 node:n2 leaf: l2 leaf: l3
適当に笑い飛ばしてください。最後の、catch (Base b) が気にくわない。まぁなんというか。こんなの実際に使うわけじゃないけどね・・・。