【问题标题】:Tail recursion - will this make optimal use of frame and how do I check if compiling as tail recursive?尾递归 - 这会优化使用帧吗?如何检查编译是否为尾递归?
【发布时间】:2013-03-29 19:31:56
【问题描述】:

在下面的代码中 - 列表的最大值和总和非常简单 - 我有一个在方法末尾调用的递归函数。 scala 编译器会将其视为尾递归并优化堆栈帧的使用吗?我怎么知道/如何验证这一点?

package example

import common._

object Lists {
  def sum(xs: List[Int]): Int = {

    def recSum(current: Int, remaining: List[Int]): Int = {
      if (remaining.isEmpty) current else recSum(current + remaining.head, remaining.drop(1))
    } 

    recSum(0, xs)
  }

  def max(xs: List[Int]): Int = {

    def recMax(current: Int, remaining: List[Int], firstIteration: Boolean): Int = {
      if(remaining.isEmpty){
        current
      }else{
        val newMax = if (firstIteration || remaining.head>current) remaining.head else current
        recMax(newMax, remaining.drop(1), false)
      }
    }

    if (xs.isEmpty) throw new NoSuchElementException else recMax(0, xs, true)
  }
}

【问题讨论】:

标签: scala tail-recursion


【解决方案1】:

在函数定义前添加@tailrec,使编译器对非尾递归方法产生错误:) 此外,当编译器以这种方式对其进行优化时,您必须假设该函数与命令式循环(又名 for/while 循环)一样高效。

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2010-10-04
    • 2015-06-16
    • 2020-05-03
    相关资源
    最近更新 更多