Reputation:
In my understanding, when there is need apply function for each element in list, we use fold function, right?
If just iterate the list, foreach is enough?
Upvotes: 1
Views: 2387
Reputation: 4753
fold
Use fold
when you wish to aggregate a set into a single value. Here we say, start at zero and add each successive element to the previous one, then return the result once the set is exhausted.
scala> List(1, 2, 3).foldLeft(0){ (a, b) => a + b }
res10: Int = 6
Note that fold
is designed for parallel computation but foldLeft
and foldRight
are more powerful in terms of what types they can be applied to.
map
Use map
when you want to apply a function to each element in the set and return another set with the results.
scala> List(1, 2, 3).map(x => x + x)
res12: List[Int] = List(2, 4, 6)
foreach
Use foreach
when you don't want to return anything but need some side effect eg. saving each value to a DB.
List(1, 2, 3).foreach(x => saveToDB(x))
Upvotes: 6
Reputation: 6122
In my understanding, when there is need apply function for each element in list, we use fold function, right?
Nope. You use fold when you want to get a result that is a function of all the elements in the list. That is, you fold
the list into one result
To apply the same function on each element of a list, mostly for side effects like printing to screen, you use the foreach
, hence the name.
Upvotes: 5
Reputation: 848
If you want to reduce list you are using fold
List(1,2,3,4).fold(0){_+_} <<-- gives you sum of elements in list
Foreach is used to iterate list and for example print all elements
List(1,2,3,4).foreach(println)
Upvotes: 2