Scala-yield 可以在 for 循环中多次使用吗?
举个例子:
val l = List(1,2,3)
val t = List(-1,-2,-3)
我可以做这样的事情吗?
for (i <- 0 to 10) yield (l(i)) yield (t(i))
基本上我想为每次迭代产生多个结果。
An example:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
目前尚不清楚您要求什么 - 您期望多重收益的语义是什么。 但有一点是,您可能永远不想使用索引来导航列表 - 每次调用 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
And here's another possibility that you might be asking for
The later is just syntactic sugar for
A third possibility is you want to interleave them
That's syntax sugar for
不,您不能使用多个yield 子句,但有一些解决方法。 例如:
当然,您可以嵌套 for 推导式,但这会产生一个元素列表的列表,我认为这不是您想要的。
No, you can't use multiple yield clauses, but there are work-arounds. For example:
You can nest for-comprehensions, of course, but that would result in a list of lists of elements, which I don't believe is what you want.
产量可以嵌套,这会导致......
向量的向量:
扁平化的解决方案在语义上是不同的。
Yields can be nested, which would result ...
in a Vector of Vector:
The flattened solution is semantically different.
这是一个与类型无关的解决方案,适用于未知数量的列表中未知的、变化数量的元素:
对于 2 个列表,它是过度设计的。 你虽然可以称它为
Here is a type-agnostic solution for an unknown, varying number of elements in a unknown number of lists:
For 2 Lists it is overengineered. You could although call it
显然不是。 当我尝试时出现编译错误。
看起来 for..yield 是一个表达式。 你不能有两个收益,因为这并不是表达式的真正一部分。
如果您想生成多个值,为什么不将它们生成为元组或列表呢?
例如:
Apparently not. I get a compile error when I try it.
It looks like for .. yield is an expression. You can't have two yields, since that's not really part of the expression.
If you want to yield multiple values, why not yield them as a tuple or a list?
For example:
也许yield不是最好的方法? 也许这里可以使用简单的数组附加。
Maybe yield is not the best way to go? Perhaps simple array appending could be used here.