使用 Scala 中的 for 循环中的值填充列表
我对 scala 很陌生,我无法解决这个(相当)微不足道的问题。
我知道我可以用这样的预定义值实例化一个列表:
val myList = List(1,2)
我想用从 1 到 100000 的所有整数填充一个列表。我的目标不是使用 var 作为列表并使用循环来填充列表。
有没有什么“功能性”的方法可以做到这一点?
I'm pretty new to scala and I am not able to solve this (pretty) trivial problem.
I know I can instantiate a List with predefined values like this:
val myList = List(1,2)
I want to fill a List with all Integers from 1 to 100000 . My Goal is not to use a var for the List and use a loop to fill the list.
Is there any "functional" way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其中任何一个都可以解决问题。 (不过,如果您在 REPL 中尝试它们,请注意,它将尝试打印所有
million十万个条目,这通常是行不通的。)Either of these will do the trick. (If you try them in the REPL, though, be advised that it's going to try to print all
millionhundred thousand entries, which is generally not going to work.)我对 Scala 也很陌生,它非常棒,不是吗?
雷克斯有绝对正确的答案,但值得深思:如果你想要一个不预先评估的列表(也许评估列表中的项目所涉及的计算成本很高,或者你只是想让事情变得懒惰),你可以使用 Stream。
这可以在大多数使用列表的情况下使用。
I am also very new to Scala, it's pretty awesome isn't it.
Rex has the absolutely correct answer, but as food for thought: if you want a list that is not evaluated up front (perhaps the computations involved in evaluating the items in the list is expensive, or you just want to make things lazy), you can use a Stream.
This can be used in most situations where you'd use a List.