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(_))
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 (_)
)
This operation is called foldMap
, and you can find it in Scalaz.
list foldMap transform
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With