Let,s see something
(1 to 3).foldRight(3)(_-_) == -1
(1 to 3).foldLeft(3)(_-_) == -3
why it is different
foldLeft定义:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this.seq foreach (x => result = op(result, x))
result
}
foldRight定义:
def foldRight[B](z: B)(op: (A, B) => B): B =
reversed.foldLeft(z)((x, y) => op(y, x))
下面我们来解释foldLeft和foldRight的不同之处:
(1 to 3).foldRight(3)(_-_) == -1
(1 to 3).foldLeft(3)(_-_) == -3
foldLeft:3-1-2-3 == -3
foldRight:3-(2-(1-3)) == -1
我们发现foldLeft和foldRight是完全对称的,所以如果我们交换一下f的参数位置
object file {
def main(args:Array[String])
{
println((1 to 3).foldRight(3)((i,sum)=>sum-i))
println((1 to 3).foldLeft(3)((i,sum)=>i-sum)) //exchange sum & i
}
}
result:
-3
-3
就会得到一样的结果