0

在下面的函数中(在 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
4

1 回答 1

2

To understand what's going on, change your case statement to this:

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

You get this output:

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

You can see that the zero entries result from calling sum(ys) on an empty list. Note that your result is 13.

// Assign the result to a val
val result = sum(List(3,4,5,1)) 
于 2013-09-17T21:07:16.957 回答