Java 尾递归

import java.math.BigDecimal;
import java.util.stream.Stream;

public class TailSelf {
    public static void main(String[] args) {
        System.out.println(factorial(1000000));
    }

    public static String factorial(final long number) {
        return tailRecursion(number, new BigDecimal(1)).invoke().toString();
    }

    private static TailLoop tailRecursion(long n, BigDecimal total) {
        if (n == 1) {
            return new TailLoop() {
                @Override
                public TailLoop functionalMethod() {
                    return null;
                }

                public BigDecimal result() {
                    return total;
                }
            };
        }
        return () -> tailRecursion(n - 1, total.multiply(new BigDecimal(n)));
    }

    @FunctionalInterface
    interface TailLoop {

        TailLoop functionalMethod();

        default T result() {
            return null;
        }

        default T invoke() {
            // 惰性求值
            return Stream.iterate(this, TailLoop::functionalMethod).filter((loop) -> loop.result() != null).findFirst()
                    .get().result();
        }
    }

}

知识点

  • 尾递归
  • 惰性求值
  • java8 : lambda Stream
  • 柯里化

你可能感兴趣的:(Java 尾递归)