Scala 中的 zipWith(映射多个 Seq) [英] zipWith (mapping over multiple Seq) in Scala

查看:15
本文介绍了Scala 中的 zipWith(映射多个 Seq)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

val foo : Seq[Double] = ...
val bar : Seq[Double] = ...

并且我希望生成一个 seq,其中 baz(i) = foo(i) + bar(i).我能想到的一种方法是

and I wish to produce a seq where the baz(i) = foo(i) + bar(i). One way I can think of to do this is

val baz : Seq[Double] = (foo.toList zip bar.toList) map ((f: Double, b : Double) => f+b)

然而,这感觉既丑陋又低效——我必须将两个 seq 都转换为列表(这会因惰性列表而爆炸),创建这个临时元组列表,只映射它并让它进行 GC.也许流解决了懒惰的问题,但无论如何,这感觉不必要地丑陋.在 lisp 中,map 函数会映射多个序列.我会写

However, this feels both ugly and inefficient -- I have to convert both seqs to lists (which explodes with lazy lists), create this temporary list of tuples, only to map over it and let it be GCed. Maybe streams solve the lazy problem, but in any case, this feels like unnecessarily ugly. In lisp, the map function would map over multiple sequences. I would write

(mapcar (lambda (f b) (+ f b)) foo bar)

并且不会在任何地方创建临时列表.Scala 中是否有 map-over-multiple-lists 函数,或者 zip 与解构相结合真的是正确"的方法吗?

And no temporary lists would get created anywhere. Is there a map-over-multiple-lists function in Scala, or is zip combined with destructuring really the 'right' way to do this?

推荐答案

您想要的函数名为 zipWith,但它不是标准库的一部分.它将在 2.8(更新:显然不是,请参阅评论).

The function you want is called zipWith, but it isn't a part of the standard library. It will be in 2.8 (UPDATE: Apparently not, see comments).

foo zipWith((f: Double, b : Double) => f+b) bar

请参阅这张Trac票.

这篇关于Scala 中的 zipWith(映射多个 Seq)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆