IK.AM

@making's tech note


seven(times(five()));が35を返すような関数をJavaで実装する

🗃 {Programming/Java/Lambda}
🏷 Java 🏷 Java SE 8 
🗓 Updated at 2014-05-28T19:18:01Z  🗓 Created at 2014-05-28T19:18:01Z   🌎 English Page

Twitter上でみたのでJavaでやってみた。

JavaScriptの問題。seven(times(five())); // must return 35となるような関数seven, times, fiveを作れ

Java8だと簡単ですね。(Java7より)

public class Foo {
    public static void main(String[] args) {
        System.out.println(seven(times(five()))); // 35
    }

    public static int seven(IntUnaryOperator operator) {
        return operator.applyAsInt(7);
    }

    public static IntUnaryOperator times(ToIntFunction<IntUnaryOperator> right) {
        return left -> right.applyAsInt((x) -> left * x);
    }

    public static ToIntFunction<IntUnaryOperator> five() {
        return operator -> operator.applyAsInt(5);
    }
}

↓のように書いた方が汎用的。

public class Foo {
    public static void main(String[] args) {
        System.out.println(seven(times(five())));
    }

    public static int seven(IntUnaryOperator operator) {
        return leftArgumentWith(7, operator);
    }

    public static IntUnaryOperator times(ToIntFunction<IntUnaryOperator> right) {
        return operator((x, y) -> x * y, right);
    }

    public static ToIntFunction<IntUnaryOperator> five() {
        return rightArgumentWith(5);
    }

    public static int leftArgumentWith(int left, IntUnaryOperator operator) {
        return operator.applyAsInt(left);
    }

    public static IntUnaryOperator operator(IntBinaryOperator binaryOperator, ToIntFunction<IntUnaryOperator> right) {
        return left -> right.applyAsInt((x) -> binaryOperator.applyAsInt(left, x));
    }

    public static ToIntFunction<IntUnaryOperator> rightArgumentWith(int right) {
        return operator -> operator.applyAsInt(right);
    }
}

✒️️ Edit  ⏰ History  🗑 Delete