July 2017
Intermediate to advanced
284 pages
6h 45m
English
Continuing with the stock prices example, you’re asked to write a function that will total the prices given in a collection. You figure a simple iteration is sufficient, and you write:
| | val prices = List(10, 20, 15, 30, 45, 25, 82) |
| | def totalAllPrices(prices : List[Int]) = { |
| | prices.foldLeft(0) { (total, price) => |
| | total + price |
| | } |
| | } |
In the totalAllPrices function, the foldLeft method of the list is used to compute the total in a functional style with pure immutability. You pass a function value to the foldLeft method. This function value accepts two parameters and returns the total of these two parameters. The foldLeft method invokes the function value as many times as the number of elements ...
Read now
Unlock full access