如何获得 Scala 中两个列表的平方和?
如果我有两个列表,
val first = List(1, 2, 3)
val second = List(4, 5, 6)
我如何获得以下内容?
(1-4)^2 + (2-5)^2 + (3-6)^2
If I have two lists
val first = List(1, 2, 3)
val second = List(4, 5, 6)
How would I obtain the following?
(1-4)^2 + (2-5)^2 + (3-6)^2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
zip、map 和 sum:
(编辑以
sum
替换reduceLeft
))看到评论后,我觉得我必须回来解释一下视图。基本上,视图将
Traversable
转换为类似迭代器的结构,以便在应用map
、zip
等方法时不必创建多个中间结构> 以及其他一些。 GenIteratableViewLike 的类型成员给人一种哪些操作有特殊处理。因此,通常如果您有一堆按顺序应用的 map、filter、drop、takeWhile,您可以使用 view 来获得一些性能。经验法则是尽早应用view
以最大程度地减少创建的中间List
数量,如有必要,在最后使用force
返回到List
(或您正在使用的任何集合)。这就是丹尼尔的建议。关于性能的问题是,在实践中,如果这很重要,你就必须进行现实检查。以下是一些数字(越低越好):
代码在这里:
zip, map and sum:
(edit to replace
reduceLeft
bysum
)After seeing the comments, I feel I had to come back and explain about views. Basically a view turns a
Traversable
into an iterator like structure so that multiple intermediate structures don't have to be created when apply methods likemap
,zip
and a few others. The type members of GenIteratableViewLike gives a sense of what operations have special processing. So typically if you have a bunch of map, filter, drop, takeWhile applied in sequence, you can use view to gain some performance. The rule of thumb is to applyview
early to minimize how many intermediateList
are created and if necessary useforce
at the end to go back toList
(or whatever collection you're using). Thus Daniel's suggestion.The thing about performance is that in practice if that's important you sort of have to do a reality check. Here are some numbers (lower is better):
Code is here:
一般来说,如果函数很复杂,您可能想要定义一个函数,而不是应用多个映射。您可以将其作为辅助方法执行,或者以匿名方式内联执行。
或者
在这些情况下
zipped
比zip
更方便,因为它可以映射到带有 2 个参数的函数,而不是必须使用的单个元组._1
和._2
字段。In general you probably want to define a function if it's anything complex, rather than applying multiple maps. You can do this as a helper method, or anonymously in-line.
Or
zipped
is a bit more convenient thanzip
in these situations, because it can be mapped to a function taking 2 arguments, rather than a single tuple on which you have to use the._1
and._2
fields.向左折叠:
从拉链开始。
with a left fold:
starting with a zip.