java - 执行 "max"的功能方法(使用递归/不使用可变变量)

标签 java scala functional-programming

使用命令式代码在未排序的数组中查找最大值非常简单

例如在Java中(我相信它可以写得更好,仅用于说明目的)

public class Main {
    public static void main(String[] args) {
        int[] array = {1,3,5,4,2};
        int max = findMax(array);
        System.out.println(max);
    }

    public static int findMax(int[] array){
        int max = Integer.MIN_VALUE; //or array[0], but it requires a null check and I want to keep it simple :)
        for (int i = 0, size = array.length; i < size ; i++) {
            int current = array[i];
            if(current > max) max = current;
        }
        return max;
    }
}

这样做的功能方法是什么?例如

  • 没有可变变量(例如,使 max 在 Scala 中成为 val/在 Java 中成为 final)
  • 没有循环(例如使用递归,tail 首选)

在 Scala 的源代码中我看到它是使用 recudeLeft 完成的,这看起来很聪明

  def max[B >: A](implicit cmp: Ordering[B]): A = {
    if (isEmpty)
      throw new UnsupportedOperationException("empty.max")

    reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
  }

但假设我没有(出于某种原因)reduce/reduceLeft 可用/已实现(并且由于某种原因我不想/不能实现它,即我正在使用纯 Java)

在不依赖其他函数方法的情况下,“惯用”函数方法是什么(例如,我将如何在简单的 Java 中实现它,但要牢记函数范例)

答案可以使用任何语言(但首选 Java/Scala)

最佳答案

这是一个带有最大值累加器的尾调用递归实现。

public class Main {

    public static void main(String[] args) {
        System.out.println(max(new int[]{6, 3, 9, 4}));
    }

    public static int max(int[] ints) {
        return max(ints, Integer.MIN_VALUE);
    }

    public static int max(int[] ints, int max) {
        if (ints.length == 0) {
            return max;
        } else {
            return max(Arrays.copyOfRange(ints, 1, ints.length), ints[0] > max ? ints[0] : max);
        }
    }

}

关于java - 执行 "max"的功能方法(使用递归/不使用可变变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157108/

相关文章:

java - Spring Reactive - 收集一系列分页结果作为所有结果的 Mono

java - scala 和 java io 和套接字问题

java - Akka 是否有一个 ExecutorCompletionService 等效项,其中 Futures 按其完成时间排队?

haskell - Haskell 中的 "lifting"是什么?

java - 使用 Ant 将文本附加到目录中的多个文件

java - 从 BlackBerry 上的自定义上下文菜单中删除默认项目

java - 将对象添加到 ArrayList

scala - Scala 编程语言有哪些可用的解析器?

.net - 为什么 F# 中存在大写命名模式?

使用函数式编程和异步的 JavaScript while 循环