使用 Java 8 实现递归 lambda 函数 [英] Implement recursive lambda function using Java 8

查看:37
本文介绍了使用 Java 8 实现递归 lambda 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 引入了 lambda 函数,我想实现类似 factorial 的东西:

Java 8 introduced lambda functions and I want to implement something like factorial:

 IntToDoubleFunction fact = x -> x == 0 ? 1 : x * fact.applyAsDouble(x-1);

编译返回

  error: variable fact might not have been initialized

我如何引用函数本身.类是匿名的,但实例存在:它被称为fact.

How can I reference function itself. Class is anonymous but instance exists: It is called fact.

推荐答案

我通常使用(once-for-all-functional-interfaces defined)通用辅助类,它包装了函数式接口类型的变量.这种方式解决了局部变量初始化的问题,让代码看起来更清晰.

I usually use (once-for-all-functional-interfaces defined) generic helper class which wraps the variable of the functional interface type. This approach solves the problem with the local variable initialization and allows the code to look more clearly.

如果出现这个问题,代码将如下所示:

In case of this question the code will look as follows:

// Recursive.java
// @param <I> - Functional Interface Type
public class Recursive<I> {
    public I func;
}

// Test.java
public double factorial(int n) {

    Recursive<IntToDoubleFunction> recursive = new Recursive<>();
    recursive.func = x -> (x == 0) ? 1 : x * recursive.func.applyAsDouble(x - 1);

    return recursive.func.applyAsDouble(n);
}

这篇关于使用 Java 8 实现递归 lambda 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆