Scala中的尾递归平均值(算术平均值)

时间:2015-01-18 22:34:59

标签: scala mean tail-recursion

我想编写尾递归函数,它将整数列表作为参数,并返回该列表的平均值(算术平均值)。

示例:mean(List(1,2,3,4))= 2.5

def mean(as: List[Int]):Float={
        def helper(as: List[Int], accumulator_length:Int,accumulator_sum:Int):Float={
        as match{
          case Nil=>accumulator_sum.toFloat/accumulator_length
          case x::xs=>helper(xs,accumulator_length+1,accumulator_sum+x)
        }
      }
      helper(as,0,0)
    }

我假设上面的函数完全是尾递归的,但是,有没有简单的方法来跟踪Scala中的函数求值?

1 个答案:

答案 0 :(得分:2)

显而易见的方法是记录你的函数的调用:

scala> @tailrec def mean(lst: List[Int], acc: Int = 0, size: Int = 0): Double = {
    |     println(s"lst = $lst, acc = $acc, size = $size") 
    |     if (lst.isEmpty) acc.toDouble/size 
    |       else mean(lst.tail, acc + lst.head, size + 1)
    |  }
mean: (lst: List[Int], acc: Int, size: Int)Double

scala> mean(List(1,2,3,4))
lst = List(1, 2, 3, 4), acc = 0, size = 0
lst = List(2, 3, 4), acc = 1, size = 1
lst = List(3, 4), acc = 3, size = 2
lst = List(4), acc = 6, size = 3
lst = List(), acc = 10, size = 4
res4: Double = 2.5 //this one printed by Scala REPL

所以你可以在没有IDE的情况下跟踪它