【问题标题】:Scala Stream "isEmpty" method VS pattern matching "head #:: tail"Scala Stream“isEmpty”方法VS模式匹配“head #::tail”
【发布时间】:2013-11-21 20:35:22
【问题描述】:

当我调试时,它显示“$Stream$Empty”。但它不属于 .isEmpty 案例。我将模式更改为“head #::tail”,它在某些测试用例中运行良好。谁能解释一下幕后发生了什么?

【问题讨论】:

  • 你需要显示实际代码。
  • 推测:流是非空的,因为它有元素,但还没有实现这些元素。
  • :( 代码与 Coursera 函数式编程课程的作业相关。

标签: scala stream is-empty


【解决方案1】:

这有用吗? isEmpty 效果很好。

val strm = true #:: false #:: Stream[Boolean]()
def matchStream[T](stream:Stream[T]):List[String] = {
  stream match {
    case head #:: tail => head.toString :: matchStream(tail)
    case stm if stm.isEmpty => List("end of stream")
  }
}
matchStream(strm)

我在工作表中运行了这个并得到了

res0: List[String] = List(true, false, end of stream)

【讨论】:

  • 这是一个关于调试器输出的 3 年老问题,您的答案没有解决。我怀疑 OP(一年多没有访问过 SO)或其他任何人会觉得这很有帮助。
猜你喜欢
  • 2021-03-25
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2021-12-17
  • 2011-06-28
相关资源
最近更新 更多