言語仕様ベンチマーク
昨日のクロージャもどきの続き。ちょっと改良してみた。
言語仕様のベンチマークといえる、加算器を生成する関数。
interface F1<T,A> { T call(A a);} //引数一つなら interface F2<T,A,B>{ T call(A a,B b);} //引数二つなら。。 public class Test { public static F1<Integer,Integer> getAccumulator(final Integer a) { return new F1<Integer,Integer>() { Integer m = a; public Integer call(Integer add){ return this.m += add; } }; } public static void main(String[] args) { F1<Integer,Integer> accumulator = getAccumulator(5); System.out.println(accumulator.call(1)); System.out.println(accumulator.call(1)); System.out.println(accumulator.call(1)); } }
あいかわらずfinal指定がイマイチなのと、interfaceを引数の個数に応じて用意しなければならない。もう一歩改良できないのだろうか。
だけど、それ以外は結構いいカンジだと思う。型に厳しい関数型言語みたいでカッコよくない? 意外に実用に耐えると思う。Visitorパターン(ダブルディスパッチ)とかに応用できそう*1。Treeをトラバースする際に渡される引数(ノード)と、Visitorの組み合わせに応じて、それを処理する匿名クラス(のインスタンス)を生成して実行してウハウハという感じ。<-むずかしいかも。
*1:ちょっとテキトーな意見