scala> def f(x:Int) = return x+1 //The return type cannot be inferred, so the return type must be explicitly stated to avoid errors
<console>:11: error: method f has return statement; needs result type
def f(x:Int) = return x+1
^
scala> def f(x:Int):Int = return x+1
f: (x: Int)Int
scala> def f2(x:Int) = x+1
f2: (x: Int)Int
The following code is not very clear (mainly I don't understand foldLeft)
scala> def add(n:Int,m:Int):Int = return n+m
add: (n: Int, m: Int)Int
scala> def sum1(ns:Int*):Int = ns.foldLeft(0)((n,m)=> return n+m)
sum1: (ns: Int*)Int
scala> println(sum1(1,2,3)) //Formula 1.1
1 //This result is really not understood????
scala> def sum2(ns:Int*):Int = ns.foldLeft(0)(add)
sum2: (ns: Int*)Int
scala> println(sum2(1,2,3)) //Formula 1.2
6
In the above code, you need to figure out the foldLeft function first, and do some experiments below:
scala> val numbers = List(5,4,8,6,2)
numbers: List[Int] = List(5, 4, 8, 6, 2)
scala> numbers.fold(0){(z,i)=>z+i}
res11:
Why does Int = 25 print the result as 25?
val numbers = List(5,4,8,6,2)
println(numbers.foldLeft(0){(z,i)=>z+i})
println(numbers.foldLeft(1){(z,i)=>z+i})
println(numbers.foldLeft(2){(z,i)=>z+i})
The result printed is:
25
26
27
what about this? Looking at the source code in scala below, you can know that Z is actually the initial total value, and Z is the sum value when adding halfway. So the result printed out is 25, 26, 27.
in scala.collection.TraversableOnce
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this foreach (x => result = op(result, x))
result
}
Looking back at Equation 1.1
That is to say, in the foldLeft function, when result=0, x=1 is added, and then 1 is returned. At this time, the return n+m instruction is encountered, and the return in scala will exit the entire function, so the return result is 1. And formula 1.2 is only returned by the function add, not by the anonymous function in foldLeft, so the result is 6