schmmd
schmmd

Reputation: 19468

summing a transformation of a list of numbers in 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(_))

Upvotes: 7

Views: 419

Answers (2)

missingfaktor
missingfaktor

Reputation: 92046

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

list foldMap transform

Upvotes: 5

Luigi Plinge
Luigi Plinge

Reputation: 51109

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 (_))

Upvotes: 12

Related Questions