【问题标题】:Stream of readLinesreadLines 流
【发布时间】:2010-07-22 06:11:37
【问题描述】:

我正在尝试从 readLine 调用中创建无限的字符串流:

import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input: Stream[String] = Stream.cons(in readLine, input)

但似乎 readLine 调用并没有被懒惰地调用。输入该代码后,readLine 立即需要输入,然后 Stream 成为相同输入的无限列表。有没有可能实现我的想法?

【问题讨论】:

    标签: scala input stream scala-2.8 lazy-evaluation


    【解决方案1】:
    import java.io.{BufferedReader, InputStreamReader}
    val in = new BufferedReader(new InputStreamReader(System in))
    val input = Stream.continually(in readLine)
    

    【讨论】:

    • 不需要关闭流吗?
    【解决方案2】:

    参见Stream 的示例。请注意,惰性重击在尾部,而不是头部。每次调用 thunk 时,它都应返回下一个 cons(包括下一个 thunk,而下一个 thunk 又应提供下一个 cons incl ....)

    这是 Stream.cons 的签名:http://www.scala-lang.org/docu/files/api/scala/collection/immutable/Stream$$cons$.html>。注意 thunk (=> Stream) 作为 apply 的第二个参数。

    【讨论】:

      猜你喜欢
      • 2016-04-27
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多