将 Iterable.sliding 输出为元组
集合上的方法 sliding 以 X[Iterable[A]]
的形式返回给定大小的滑动窗口,其中 X 是集合类型,A 是元素类型。通常我需要两个或三个元素,并且我更喜欢给它们命名。 sliding(2)
的一个丑陋的解决方法如下:
points.sliding(2).foreach{ twoPoints =>
val (p1,p2) = (twoPoints.head,twoPoints.last)
//do something
}
这很糟糕并且仅适用于两个元素。另请注意,这
(a,b) = (twoPoints(0),twoPoints(1))
不起作用。
The method sliding on collections returns a sliding window of given size in the form of X[Iterable[A]]
with X being the type of the collection and A the element type. Often I need two or three elements and I prefer to have them named. One ugly workaround for sliding(2)
is the following:
points.sliding(2).foreach{ twoPoints =>
val (p1,p2) = (twoPoints.head,twoPoints.last)
//do something
}
This sucks and only works for two elements. Also note that
(a,b) = (twoPoints(0),twoPoints(1))
doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在 这个 上周就回答了。
如果
points
是Array
,则将X
替换为Array
。如果是List
,则将X
替换为List
,依此类推。请注意,您正在进行模式匹配,因此您需要使用
{}
而不是参数的()
。I did a lot of that in this answer just last week.
If
points
is anArray
, then replaceX
withArray
. If it is aList
, replaceX
withList
, and so on.Note that you are doing a pattern match, so you need to
{}
instead of()
for the parameter.twoPoints
看起来是一个列表。试试这个:你会惊讶地发现什么样的功夫模式匹配可以让你侥幸逃脱。
twoPoints
would appear to be a List. Try this:You'll be surprised what sorts of kung fo pattern matching lets you get away with.
我最近想在滑动迭代器中添加更多糖分,所以我想出了这个:
这适用于任何
Seq
,但对于List
可能最有效。.zipped
返回scala.runtime.Tuple2Zipped
(或Tuple3Zipped
(用于 3 元素元组)对象,它定义了几个熟悉的高阶方法,以便它们的参数采用多个参数,因此您可以编写:甚至:
您可以优化如果您希望它对非列表类型真正有效,请进一步实现。
I recently wanted a little more sugar in my sliding iterators, so I came up with this:
This works with any
Seq
, but is probably most efficient withList
..zipped
returns ascala.runtime.Tuple2Zipped
(orTuple3Zipped
for a 3-element tuple) object, which defines several familiar higher-order methods so that their arguments take multiple arguments, so you can write:or even:
You can optimize the implementation further if you want it to be really efficient for non-list types.