LoginSignup
11
10

More than 5 years have passed since last update.

Yコンビネータでラムダ式が再帰関数に変わるからフィボナッチ数も計算できる、Java8版

Last updated at Posted at 2014-04-22

Yコンビネータと言いつつZコンビネータじゃね?

Program.java
package example;

import java.util.function.*;

public class Program {

    public static void main(String[] args) {

        Function<Integer, Integer> fib
            = Y(f -> n -> n > 1 ? f.apply(n - 1) + f.apply(n - 2) : n);
        System.out.println(fib.apply(8));
    }

    static <A, R> Function<A, R> Y(
        Function<Function<A, R>, Function<A, R>> f) {
        Recursive<A, R> rec1 = r -> a -> f.apply(r.applyRec(r)).apply(a);
        Recursive<A, R> rec2 = r -> a -> f.apply(r.applyRec(r)).apply(a);
        return rec1.applyRec(rec2);
    }
}

@FunctionalInterface
interface Recursive<A, R> {
    public Function<A, R> applyRec(Recursive<A, R> f);
}
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10