gpt4 book ai didi

java - 函数式接口(interface)和递归

转载 作者:行者123 更新时间:2023-12-01 19:28:27 25 4
gpt4 key购买 nike

我需要返回一个函数,该函数返回将函数 f 应用于其结果 n 次的结果。我的代码:

public <T> Function<T, T> fN(Function<T, T> f, int n) {
return (T t) -> fN(f, n - 1).apply(t);
}

当我运行代码时,我得到 java.lang.StackOverflowError 。我该如何编写这段代码才能通过以下测试?

Function<Integer, Integer> f1 = (x) -> x + 1;
assertEquals(13, (int)tasks.fN(f1, 13).apply(0));
assertEquals(2, (int)tasks.fN(f1, 1).apply(1));

感谢您的帮助。

最佳答案

非递归、简单的方法:

public <T> Function<T, T> nonRecursiveFN(Function<T, T> f, int n) {
return (T t) -> {
T result = t;
for (int i = 0; i < n; i++) {
result = f.apply(result);
}
return result;
};
}

如果您需要使用递归,您需要一些停止条件,正如安德烈亚斯评论的那样。我们可以通过使用内部函数来实现它,该函数以已经构造的函数作为参数:

public <T> Function<T, T> fN(Function<T, T> f, int n) {
return fNInternal(f, n, (x) -> x); //we start with identity function
}

public <T> Function<T, T> fNInternal(Function<T, T> f, int remaining, Function<T, T> functionSoFar) {
//stop condition - that's how we manage to avoid StackOverflow, you were experiencing
if (remaining == 0) {
return functionSoFar;
}
//here we apply function to the result of all previous applications
return fNInternal(f, remaining - 1, (T t) -> f.apply(functionSoFar.apply(t)));
}

关于java - 函数式接口(interface)和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60645452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com