简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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