【问题标题】:A recursive lambda TriFunction [duplicate]递归 lambda TriFunction [重复]
【发布时间】:2020-07-13 21:12:59
【问题描述】:

这是在不声明自己的接口的情况下实现“TriFunction”的最佳方式吗?那个构造是怎么命名的?

import java.util.function.BiFunction;
import java.util.function.Function;

public class Rec {
    public static Function<Integer, Function<Integer, Function>> myPowerTriFunction = x -> y -> f -> y == 0 ? 1 : x * (Integer) ((Function<Integer, Function<Integer, Function>>) f).apply(x).apply(y - 1).apply(f);
    public static BiFunction<Integer, Integer, Integer> myPowerBiFunction = (x, y) -> (Integer) myPowerTriFunction.apply(x).apply(y).apply(myPowerTriFunction);

    public static void main(String[] args) {
        System.out.println(myPowerBiFunction.apply(3, 5)); // Prints 243
    }
}

【问题讨论】:

  • 您为什么不想定义自己的界面?比写这个问题花费的时间更少。
  • 在我看来,您已经指定了双功能的要求。您的示例接受 2 个参数并返回一个值,这就是双函数的作用。您已经隐藏了函数中的一些复杂性,但这并不能真正使它成为三函数。三函数将采用 3 个值并返回 1。如果这是您需要的,我认为您会想要/需要创建一个接口。一个很好的例子可以在这个答案中找到:stackoverflow.com/a/19649473/2124562。
  • 这是递归的,所以它实际上不是另一个问题的重复,是吗?
  • 如果你想让Function 对象是递归的,试试Y 组合器之类的东西。这是一个基本的 Java 实现 - repl.it/repls/GenuineSeashellBootstrapping(注意:这不是实际的 Y-combinator,它需要定义一个接口,因为它使用递归类型)
  • @user 是的,这实际上并不是另一个问题的重复...也许这个问题可以重新打开...非常感谢您的回答。 :)

标签: java recursion lambda


【解决方案1】:

您正在尝试使用一种称为currying 的技术。基本思想是两个或多个参数f(x, y) 的函数可以表示为返回函数f(x)(y) 的函数。

例如,这是一个添加 3 个数字的“咖喱”函数:

public static Function<Integer, Function<Integer, Function<Integer, Integer>>>
    sum3 = x -> y -> z -> x + y + z;

这种风格并不真正适合 Java,因为该语言的一个关键理念是名称是有意义的。创建匿名函数与这个想法背道而驰。

在您自己的代码中,您不应使用 Function 等原始类型。如果您不知道/不关心类型,请使用通配符 ?:

public static Function<Integer, Function<Integer, Function<?,?>>> myPowerTriFunction;

【讨论】:

  • 我知道这是公认的答案,但它没有解决 OP 想要递归函数的事实
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 2017-08-02
相关资源
最近更新 更多