我试图以函数式的方式计算阶乘。
我做了这个:
private static Function<BigInteger, BigInteger> factorial = x -> BigInteger.ONE.equals(x)
? BigInteger.ONE
: x.multiply(Main.factorial.apply(x.subtract(BigInteger.ONE)));
当我尝试获取11111
!时,我遇到了StackOverflowError
错误。
但是,如果我使用以下方法计算阶乘:
private static BigInteger factorial(BigInteger request) {
if (BigInteger.ONE.equals(request)) return BigInteger.ONE;
else return request.multiply(factorial(request.subtract(BigInteger.ONE)));
}
我可以在不出现StackOverflowError
的情况下得到结果。
函数式编程风格是否更加低效?为什么?