【问题标题】:How to properly use Stream's iterate and takeWhile constructs?如何正确使用 Stream 的 iterate 和 takeWhile 构造?
【发布时间】:2019-10-03 03:30:00
【问题描述】:

在 Scala 2.12.x 中,我有以下示例,但它没有产生预期的结果:

val result = Stream.iterate(0)(_ + 10).takeWhile(_ < 100)
println(result)

// outputs:
// Stream(0, ?)

// while I expected:
// Stream(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, ?)

我在这里做错了什么?

【问题讨论】:

  • 它确实有效,记住 Streamlazy,因此它还没有做任何事情。您可以将其转换为 List (result.toList) 或使用 foreach(println) 来查看结果。
  • 啊,是的!就是这样:)

标签: scala stream


【解决方案1】:

在您将其转换为非惰性集合之前,您的流不会被具体化:

Stream.iterate(0)(_ + 10).takeWhile(_ < 100).toList

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 2017-08-13
    • 1970-01-01
    • 2021-05-10
    • 2016-10-06
    • 1970-01-01
    • 2016-11-04
    • 2014-01-21
    相关资源
    最近更新 更多