Summarizing the conversion of a list of numbers to scala

I often have to summarize the conversion of a list of numbers to Scala. Of course, one way to do this is:

list.map(transform(_)).sum 

However, this creates memory when the creation of memory is not required. An alternative is to collapse the list.

 list.foldLeft(0.0) { (total, x) => total + f(x) } 

I find that the first expression is much easier to write than the second expression. Is there a way that I can use that has the ease of the first with the effectiveness of the second? Or am I better off writing my own implicit method?

 list.mapSum(transform(_)) 
+7
source share
2 answers

You can use the view to make your transformer methods (map, filter ...) lazy. See here for more details.

So, for example, in your case with the transform method, you should write

 list.view.map(transform).sum 

(note that you can optionally omit (_) )

+12
source

This operation is called foldMap and can be found in Scalaz.

 list foldMap transform 
+5
source

All Articles