简体   繁体   English

Scala-惰性评估说明

[英]Scala - lazy evaluation explanation

Welcome, 欢迎,

can anyone tell me why my code is not behaving as I expect? 谁能告诉我为什么我的代码没有按我预期的方式工作? I have the following test snippet: 我有以下测试代码段:

sealed trait Stream[+A] {

import Stream._

// may cause stackOverflow for large streams
def toList: List[A] = this match {
  case Empty => Nil
  case Cons(h, t) => h() :: t().toList
}

def toList2: List[A] = {
  // stackOverflow secure solution
  def iterate(s: Stream[A], acc: List[A]): List[A] = s match {
    case Empty => acc
    case Cons(h, t) => iterate(t(), h() :: acc)
  }

  iterate(this, List()).reverse
}

def take(n: Int): Stream[A] = (n, this) match {
  case (v, Empty) if v > 0 => throw new IllegalStateException()
  case (0, _) => empty()
  case (v, Cons(h, t)) => cons(h(), t().take(n - 1))
}

def drop(n: Int): Stream[A] = (n, this) match {
  case (v, Empty) if v > 0 => throw new IllegalStateException()
  case (0, _) => this
  case (_, Cons(h, t)) => t().drop(n - 1)
}
}

case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, tl: () => Stream[A]) extends Stream[A]

object Stream {

def cons[A](h: => A, tl: => Stream[A]): Stream[A] = {
  lazy val head = h
  lazy val tail = tl
  Cons(() => head, () => tail)
}

def empty[A]():Stream[A] = Empty

def apply[A](as: A*): Stream[A] = if (as.isEmpty) empty() else cons(as.head, apply(as.tail: _*))
}

The problem is, that following test is failing (it does not throw an exception): 问题是,以下测试失败(它不会引发异常):

an [IllegalStateException] shouldBe thrownBy {
  Stream(1).take(2)
}

Maybe anyone can explain me why this is happening, because I can't debug the problem? 也许有人可以解释我为什么会这样,因为我无法调试问题?

You say it: Streams are lazy - there only evaluated by demand (because of call by name parameters). 可以这么说:流是惰性的-仅按需求进行评估(因为按名称参数进行调用)。

Use: 采用:

Stream(1).take(2).toList

to force evaluation 强制评估

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM