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

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

问题描述

假设我有

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

我希望生成一个seq,其中baz(i)= foo (i)+ bar(i)。我可以想到的一个方法是:

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

这感觉既丑陋又没有效率 - 我必须将两个序列转换为列表(使用惰性列表进行爆炸),创建这个临时的元组列表,并将其映射到它上面并让它成为GCed。也许流解决懒惰的问题,但无论如何,这感觉像不必要的丑陋。在lisp中,映射函数可以映射多个序列。我会写

 (mapcar(lambda(fb)(+ fb))foo bar)

并不会在任何地方创建临时列表。在Scala中是否有一个map-over-multiple-lists函数,还是zip与解构相结合,真的是正确的方式来做到这一点? 解决方案 div>

你想要的函数叫做 zipWith ,但它不是标准库的一部分。它将在2.8(更新:显然不是,见评论)。

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

请参阅此Trac票券


Suppose I have

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

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)

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)

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?

解决方案

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

See this Trac ticket.

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

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