Thanks Balmung San the first piece of code worked.
Great 
PS: product.reduce(+)
is the same as product.sum
But the second piece of code didn’t worked.
I assume you get a compile error like: lazyZip not found
If so, that is because lazyZip
was added on 2.13
if you are using an older version of Scala, I believe you can (u, v).zipped
instead.
Also can you tell what are lazyzip, acc and foldLeft doing.
Of course, but remember the scaladoc is your friend.
(also foldLeft
is quite a basic function that most tutorial should cover, what are you following for learning Scala?)
lazyZip
lazily zips both lists into one. What does zip
mean? Well, I guess the best way to show it is through code.
// Assume two lists:
val l1 = List(1, 2, 3, 4)
val l2 = List('a', 'b', 'c', 'd')
// Then.
val l3 = l1 zip l2
// Is the same as.
val l3: List[(Int, Char)] = List((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
So, as you can see, it joins both lists into one, element by element.
And what does the “lazily” part mean? That instead of creating the Lists of Tuples right away, it just knows that it has to do that, but it waits for a further operation to consume the tuples.
foldLeft
as the name suggests, folds (combines) all the elements of the list into one.
It receives a zero element and, a function that takes the current accumulated value and the current value of the list and returns the new accumulated value.
So:
(u lazyZip v).foldLeft(0) {
case (acc, (ui, vi)) => acc + (ui * vi)
}
0
is the zero element, so we start the accumulation with a zero
.
case (acc, (ui, vi))
the acc
is the current accumulated value, and (ui, vi)
is the current value of the list of tuples.
acc + (ui * vi)
the new accumulated value is the previous accumulated plus the product of the current tuple.
I hope that makes sense.