Scala-是否可以通过for循环多次使用yield? [英] Scala - can yield be used multiple times with a for loop?

查看:341
本文介绍了Scala-是否可以通过for循环多次使用yield?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个例子:

val l = List(1,2,3)
val t = List(-1,-2,-3)

我可以做这样的事情吗?

Can I do something like this?

for (i <- 0 to 10) yield (l(i)) yield (t(i))

基本上,我想为每个迭代产生多个结果.

Basically I want to yield multiple results for every iteration.

推荐答案

不清楚您要的是什么-您期望多重收益的语义是什么.但是,有一件事是,您可能永远不想使用索引来导航列表-每次对t(i)的调用都是O(i)来执行.

It's not clear what you're asking for - what you expect the semantics of multiple yield to be. One thing, though, is that you probably never want to use indexes to navigate a list - each call to t(i) is O(i) to execute.

所以这是您可能要问的一种可能性

So here's one possibility that you might be asking for

scala> val l = List(1,2,3); val t = List(-1,-2,-3)
l: List[Int] = List(1, 2, 3)
t: List[Int] = List(-1, -2, -3)

scala> val pairs = l zip t
pairs: List[(Int, Int)] = List((1,-1), (2,-2), (3,-3))

这是您可能要问的另一种可能性

And here's another possibility that you might be asking for

scala> val crossProduct = for (x <- l; y <- t) yield (x,y)
crossProduct: List[(Int, Int)] = List((1,-1), (1,-2), (1,-3), (2,-1), (2,-2), (2,-3), (3,-1), (3,-2), (3,-3))

后来只是语法糖

scala> val crossProduct2 = l flatMap {x => t map {y => (x,y)}}
crossProduct2: List[(Int, Int)] = List((1,-1), (1,-2), (1,-3), (2,-1), (2,-2), (2,-3), (3,-1), (3,-2), (3,-3))

第三种可能性是您想对它们进行交织

A third possibility is you want to interleave them

scala> val interleaved = for ((x,y) <- l zip t; r <- List(x,y)) yield r
interleaved: List[Int] = List(1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8, 9, -9, 10, -10)

这是语法糖

scala> val interleaved2 = l zip t flatMap {case (x,y) => List(x,y)}
interleaved2: List[Int] = List(1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8, 9, -9, 10, -10)

这篇关于Scala-是否可以通过for循环多次使用yield?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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