gpt4 book ai didi

java - 文件夹 : fold method

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:17 24 4
gpt4 key购买 nike

我在 Java 中遇到了一个问题,我有以下接口(interface)。

public interface Function2<T, U, R>
{
R apply(T t, U u);
}

public interface Folder<T, U>
{
U fold(U u, Queue<T> list, Function2<T,U,U> function);
}

并且该问题要求开发人员实现:

public class MyFolder<T, U> implements Folder<T, U>
{
public U fold(U u, Queue<T> ts, Function2<T, U, U> function)
{
if(u == null || ts == null || function == null)
throw new IllegalArgumentException();

if (ts.isEmpty()) {
return u;
}

// The recursive implementation will overflow the stack for
// any data set of real size, your job is to implement a
// non-recursive solution
//return fold(function.apply(ts.poll(), u), ts, function);
return null;
}
}

有人可以向我解释折叠功能的作用吗?我似乎无法在网上找到示例。我读过here关于此方法的作用,但没有给出任何具体示例。

最佳答案

来自维基百科:

在函数式编程中,fold——也被称为 reduce、accumulate、aggregate、compress 或 inject——指的是一系列高阶函数,它们分析递归数据结构并通过使用给定的组合操作重新组合结果递归地处理它的组成部分,建立一个返回值。通常,折叠带有组合函数、数据结构的顶部节点,以及可能在某些条件下使用的一些默认值。然后折叠继续组合数据结构层次结构的元素,以系统的方式使用函数。

http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29

哦,与评论中的实现等效的非递归是:

do {
u = function.apply(ts.poll(), u);
} while (!ts.isEmpty());
return u;

关于java - 文件夹 : fold method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22327022/

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