在 Scala 中对数字列表的转换求和 [英] summing a transformation of a list of numbers in scala
问题描述
我经常需要在 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(_))
推荐答案
您可以使用 视图 使您的转换器方法(映射、过滤器...)变得懒惰.请参阅此处了解更多信息.
You can use a view to make your transformer methods (map, filter...) lazy. See here for more information.
例如,在您使用名为 transform
的方法的情况下,您将编写
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 (_)
)
这篇关于在 Scala 中对数字列表的转换求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!