As a little Scala fold/reduce example, here’s a quick example of how to use variable names with the Scala foldLeft
method:
val pSum = movies.foldLeft(0.0)((accum, element) => accum + p1Movies(element) * p2Movies(element) )
In this example the variable movies
is a Seq
, and the variables p1Movies
and p2Movies
are Map
objects.
If you know a little about how to use foldLeft
, I hope the variable names accum
(short for accumulator) and element
are meaningful. (Jamie Allen writes that he uses the name current
for what I call element
.)
Most Scala foldLeft
, reduce
, reduceLeft
, reduceRight
examples show how to use underscores instead of variable names, so I wanted to make a note of how to use variable names.
If you also wanted to see how to use variable names with these Scala methods, I hope this example is helpful.
Another example
Here’s an example of how to write a “sum” algorithm using variable names with reduce
:
def sum(list: List[Int]): Int = list.reduce((x,y) => x + y)
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |