scala - 递归求和函数,如何限制总和?

标签 scala recursion functional-programming

目标是将这个总和编码为递归函数。 Sum

到目前为止,我已经尝试过像这样编写代码。

def under(u: Int): Int = {
    var i1 = u/2
    var i = i1+1
    if (  u/2 == 1 ) then u + 1 - 2 * 1
    else   (u + 1 - 2 * i) + under(u-1)
}

似乎我遇到了递归部分的问题,但我无法弄清楚出了什么问题。 理论上,under(5) 应该产生 10。

最佳答案

你的逻辑是错误的。它应该从 i=1 迭代到 i=n/2(无论是通过循环、递归还是集合都无关紧要)。但按原样使用 n 和当前的 i

(1 to (n/2)).map(i => n + 1 - 2 * i).sum

您(或多或少)正在从 i=1i=n(或者更确切地说,n 降至 1)运行计算,而不是 n 您使用 i/2,而不是 i 您使用 i/2+1。 ((n/2 + 1 - 2 * i) 的 i=1 到 i=n 之和)。

// actually what you do is more like (1 to n).toList.reverse
// rather than (1 to n)
(1 to n).map(i => i/2 + 1 - 2 * (i/2 + 1)).sum

这是一个不同的公式。它有两倍的元素需要求和,其中每个元素的一部分都在变化而不是恒定,而另一部分的值是错误的。

要使用递归实现相同的逻辑,您必须执行以下操作:

// as one function with default args

// tail recursive version
def under(n: Int, i: Int = 1, sum: Int = 0): Int =
  if (i > n/2) sum
  else under(n, i+1, sum + (n + 2 - 2 * i))

// not tail recursive
def under(n: Int, i: Int = 1): Int =
  if (i > n/2) 0
  else (n + 2 - 2 * i) + under(n, i + 1)

// with nested functions without default args

def under(n: Int): Int = {
  // tail recursive
  def helper(i: Int, sum: Int): Int =
    if (i > n/2) sum
    else helper(i + 1, sum + (n + 2 - 2 * i))
  helper(1, 0)
}

def under(n: Int): Int = {
  // not tail recursive
  def helper(i: Int): Int =
    if (i > n/2) 0
    else (n + 2 - 2 * i) + helper(i + 1)
  helper(1)
}

关于scala - 递归求和函数,如何限制总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69853222/

相关文章:

scala - 如何使用 Map[String,Long] 列作为 DataFrame 的头部并保留类型?

scala - 在 Scala 中处理多个 Future

Java泛型推理太宽泛?

scala - 为什么 Scala 没有为每个 monad 定义返回/单元函数(与 Haskell 相比)?

python - 如何解决我在求职面试中看到的这个递归问题?

list - Haskell:处理死锁的自引用列表

haskell - 模式匹配比 Haskell 中的 case 表达式更可取的现实示例?

f# - 如何在 F# 中的 Seq、List 或 Array 中找到 max 的索引

ruby - 在 Ruby 中按名称传递函数

Scala sortBy 参数作为序列