Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summing a transformation of a list of numbers in scala

Tags:

scala

I frequently need to sum the transformation of a list of numbers in Scala. One way to do this of course is:

list.map(transform(_)).sum

However, this creates memory when creating memory is not required. An alternative is to fold the list.

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

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

list.mapSum(transform(_))
like image 874
schmmd Avatar asked Oct 11 '11 17:10

schmmd


2 Answers

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

So for example in your case of a method called transform, you would write

list.view.map(transform).sum

(note you can optionally omit the (_))

like image 163
Luigi Plinge Avatar answered Nov 16 '22 07:11

Luigi Plinge


This operation is called foldMap, and you can find it in Scalaz.

list foldMap transform
like image 43
missingfaktor Avatar answered Nov 16 '22 07:11

missingfaktor