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) {开发者_Python百科 (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
精彩评论