为什么在这个递归函数中输出这些值?

时间:2013-09-17 20:57:20

标签: scala

在下面的函数(在Scala工作表中运行)为什么我收到sum(ys)的输出?

如何计算值0,1,0等?

def sum(xs: List[Int]): Int = xs match {
    case Nil => 0
    case y :: ys => {
        println(sum(ys))
        y + sum(ys)
    }
  }                                               //> sum: (xs: List[Int])Int

  sum(List(3,4,5,1))                              //> 0
                                                  //| 1
                                                  //| 0
                                                  //| 6
                                                  //| 0
                                                  //| 1
                                                  //| 0
                                                  //| 10
                                                  //| 0
                                                  //| 1
                                                  //| 0
                                                  //| 6
                                                  //| 0
                                                  //| 1
                                                  //| 0

1 个答案:

答案 0 :(得分:2)

要了解发生了什么,请将您的案例陈述更改为:

case y :: ys => {
    println("y: " + y + "\tys: " + ys + "\tsum(ys):" + sum(ys))
    y + sum(ys)
}

你得到这个输出:

scala> sum(List(3,4,5,1)) 
y: 1    ys: List()      sum(ys):0
y: 5    ys: List(1)     sum(ys):1
y: 1    ys: List()      sum(ys):0
y: 4    ys: List(5,1)   sum(ys):6
y: 1    ys: List()      sum(ys):0
y: 5    ys: List(1)     sum(ys):1
y: 1    ys: List()      sum(ys):0
y: 3    ys: List(4,5,1) sum(ys):10
y: 1    ys: List()      sum(ys):0
y: 5    ys: List(1)     sum(ys):1
y: 1    ys: List()      sum(ys):0
y: 4    ys: List(5,1)   sum(ys):6
y: 1    ys: List()      sum(ys):0
y: 5    ys: List(1)     sum(ys):1
y: 1    ys: List()      sum(ys):0
res0: Int = 13

您可以看到在空列表中调用sum(ys)会产生零条目。请注意,您的结果是13。

// Assign the result to a val
val result = sum(List(3,4,5,1))