关于 Scala 中的 yield 命令和以下示例:
val values = Set(1, 2, 3)
val results = for {v <- values} yield (v * 2)
谁能解释一下 Scala 如何知道要屈服于哪种类型的集合?我知道它是基于值,但是我该如何编写复制产量的代码呢?有什么办法可以改变要生成的集合的类型吗?在示例中,我希望结果的类型为List而不是Set。如果做不到这一点,从一个集合转换为另一个集合的最佳方法是什么?我知道 _:*,但由于 Set 不是 Seq 这不起作用。到目前为止我能找到的最好的是val listResults = List() ++ results。诗。我知道该示例没有遵循推荐的功能方式(即使用map),但这只是一个示例。
Concerning the yield command in Scala and the following example:
val values = Set(1, 2, 3)
val results = for {v <- values} yield (v * 2)
Can anyone explain how Scala knows which type of collection to yield into? I know it is based on values, but how would I go about writing code that replicates yield?Is there any way for me to change the type of the collection to yield into? In the example I want results to be of type List instead of Set.Failing this, what is the best way to convert from one collection to another? I know about _:*, but as a Set is not a Seq this does not work. The best I could find thus far is val listResults = List() ++ results.Ps. I know the example does not following the recommended functional way (which would be to use map), but it is just an example.
发布评论
评论(3)
for
推导式由编译器翻译为使用 这个方案。丹尼尔的精彩回答回答了您的第一个问题。
要更改结果集合的类型,您可以使用
collection.breakout
(也在我上面链接的帖子中进行了解释。)您可以将
Set
转换为List
使用以下方式之一:推荐阅读: Scala 的架构收藏
The
for
comprehensions are translated by compiler tomap
/flatMap
/filter
calls using this scheme.This excellent answer by Daniel answers your first question.
To change the type of result collection, you can use
collection.breakout
(also explained in the post I linked above.)You can convert a
Set
to aList
using one of following ways:Recommended read: The Architecture of Scala Collections
如果您使用
map
/flatmap
/filter
而不是推导式,则可以使用scala.collection.breakOut
来创建不同类型的集合:如果您想构建自己的集合类(这对我来说是最接近“复制收益”的东西),您应该看看 本教程。
If you use
map
/flatmap
/filter
instead of for comprehensions, you can usescala.collection.breakOut
to create a different type of collection:If you wanted to build your own collection classes (which is the closest thing to "replicating yield" that makes any sense to me), you should have a look at this tutorial.
试试这个:
Try this: