组合序列元素的最简洁方式
假设我们有两个序列,并且我们想要使用某种方法将它们组合起来,
val a = Vector(1,2,3)
val b = Vector(4,5,6)
例如加法可以是
val c = a zip b map { i => i._1 + i._2 }
or
val c = a zip b map { case (i, j) => i + j }
第二部分中的重复使我认为这应该可以在单个操作中实现。我看不到任何内置方法。我想我真正想要的是一种跳过元组的创建和提取的 zip 方法。
在普通的 Scala 或 Scalaz 中是否有更漂亮/更简洁的方式?如果没有,你会如何编写这样的方法并将其皮条客到序列上,这样我就可以写类似的东西
val c = a zipmap b (_+_)
Say we have two sequences and we and we want to combine them using some method
val a = Vector(1,2,3)
val b = Vector(4,5,6)
for example addition could be
val c = a zip b map { i => i._1 + i._2 }
or
val c = a zip b map { case (i, j) => i + j }
The repetition in the second part makes me think this should be possible in a single operation. I can't see any built-in method for this. I suppose what I really want is a zip method that skips the creation and extraction of tuples.
Is there a prettier / more concise way in plain Scala, or maybe with Scalaz? If not, how would you write such a method and pimp it onto sequences so I could write something like
val c = a zipmap b (_+_)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其中
可能已经足够接近您想要的内容,无需担心扩展。 (不幸的是,你不能无点地使用它,因为
zipped
上的隐式不喜欢这样。)There is
which is probably close enough to what you want to not bother with an extension. (You can't use it point-free, unfortunately, since the implicits on
zipped
don't like that.)雷克斯的答案对于大多数情况来说肯定是更简单的方法。但是,
zipped
比zip
受到更多限制,因此您可能会偶然发现它不起作用的情况。对于这些情况,您可以尝试这样做:
或者,如果您确实有一个函数或方法可以执行您想要的操作,那么您也可以选择:
使用
.tupled
将无法在第一种情况是因为 Scala 无法推断函数的类型。Rex's answer is certainly the easier way out for most cases. However,
zipped
is more limited thanzip
, so you might stumble upon cases where it won't work.For those cases, you might try this:
Or, alternatively, if you do have a function or method that does what you want, you have this option as well:
Using
.tupled
won't work in the first case because Scala won't be able to infer the type of the function.