Reputation: 6039
Define:
val a = List(1, 2, 3, 4, 5, 6, 7)
Consider the following line with foldLeft
:
a.foldLeft(""){case (num, sum) => sum + (num.toString + "-")}
My expectation was that the program is going to do:
((((( "7-" + "6-" ) + "5-" ) + "4-" ) + "3-" ) + "2-" ) + "1-"
which is 7-6-5-4-3-2-1-
But what I get is: 7654321-------
. Why is this the case?
Upvotes: 0
Views: 87
Reputation: 396
You mixed up the parameters to foldLeft
. Check the documentation for List.foldLeft
. Note that the z
"zero" value has the same type as the second parameter in the function argument, not the first.
This should work closer to expected:
a.foldLeft(""){case (sum, num) => sum + (num.toString + "-")}
// res0: String = 1-2-3-4-5-6-7-
However, if you want the numbers in reverse-order, then you might want to use foldRight
. Maybe this is actually what you were going for in the first place (notice that the arguments num
and sum
are in the same order you gave):
a.foldRight(""){case (num, sum) => sum + (num.toString + "-")}
// res1: String = 7-6-5-4-3-2-1-
Upvotes: 4
Reputation: 39587
From your expectation, I expect you expected foldRight
behavior:
scala> val a = List(1, 2, 3, 4, 5, 6, 7)
a: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala> a.foldRight(""){case (num, sum) => sum + (num.toString + "-")}
res0: String = 7-6-5-4-3-2-1-
Upvotes: 1