组合序列元素的最简洁方式

发布于 2024-11-29 19:42:25 字数 488 浏览 0 评论 0原文

假设我们有两个序列,并且我们想要使用某种方法将它们组合起来,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你对谁都笑 2024-12-06 19:42:25

其中

(a,b).zipped.map(_ + _)

可能已经足够接近您想要的内容,无需担心扩展。 (不幸的是,你不能无点地使用它,因为 zipped 上的隐式不喜欢这样。)

There is

(a,b).zipped.map(_ + _)

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.)

仅冇旳回忆 2024-12-06 19:42:25

雷克斯答案对于大多数情况来说肯定是更简单的方法。但是,zippedzip 受到更多限制,因此您可能会偶然发现它不起作用的情况。

对于这些情况,您可以尝试这样做:

val c = a zip b map (Function tupled (_+_))

或者,如果您确实有一个函数或方法可以执行您想要的操作,那么您也可以选择:

def sumFunction = (a: Int, b: Int) => a + b
def sumMethod(a: Int, b: Int) = a + b

val c1 = a zip b map sumFunction.tupled
val c2 = a zip b map (sumMethod _).tupled

使用 .tupled 将无法在第一种情况是因为 Scala 无法推断函数的类型。

Rex's answer is certainly the easier way out for most cases. However, zipped is more limited than zip, so you might stumble upon cases where it won't work.

For those cases, you might try this:

val c = a zip b map (Function tupled (_+_))

Or, alternatively, if you do have a function or method that does what you want, you have this option as well:

def sumFunction = (a: Int, b: Int) => a + b
def sumMethod(a: Int, b: Int) = a + b

val c1 = a zip b map sumFunction.tupled
val c2 = a zip b map (sumMethod _).tupled

Using .tupled won't work in the first case because Scala won't be able to infer the type of the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文