algorithm - 命令式代码的惯用 Scala 解决方案

标签 algorithm scala collections idioms

在“惯用的”Scala 中表达这个函数有什么想法。或者更准确地说,有没有一种方法可以在不牺牲可读性的情况下删除本地变量?

def solve(threshold: Int)(f: Int => Int): Int = {
  var sum = 0
  var curr = 0
  while(sum < threshold) {
   sum += f(curr)
   curr += 1
  }
  curr
}

我唯一能想出的就是这个,但我认为它更长且可读性差。

def solve2(threshold: Int)(f: Int => Int): Int = {
  val resultIterator = Iterator.iterate (0, 0) { case (curr, sum) =>
    (curr + 1, sum + f(curr))
  }
  (resultIterator find (_._2 >= threshold)).get._1
}

最佳答案

def solve(threshold: Int)(f: Int => Int): Int = {
  Iterator.from(0).map(f).scanLeft(0)(_ + _).indexWhere(threshold <=)
}

在我看来,循环版本更清晰。

关于algorithm - 命令式代码的惯用 Scala 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8683371/

相关文章:

algorithm - 编辑问题

algorithm - 在matlab中数值求解二重积分

scala - 如何将Scala Map转换为部分函数

java - 哪个系列最适合这个

java - LinkedHashMap的订单列表

c# - 在图像或笛卡尔平面中寻找负空间

c - 递归地重写一个简单的迭代算法

Scala:将数字划分为n个几乎相等长度的范围

Windows PATH 变量是否以管理员身份运行 CMD 是不同的

performance - 为什么 Scala 标准库中 @specialized 的东西这么少?