0

I'm trying to filter a stream with a predicate, but when I try to convert the stream to a list that contains an element that the predicate returns false for, I receive an error.

def machine(n:Int) = if (n==0) List(0) else List(n/2,n/3,n/4)
def greater(n:Int) = machine(n).sum > n

val d: Stream[Int] = 2 #:: d.map(_+1).filterNot(greater)

scala> d.take(11).toList
res41: List[Int] = List(2,3,4,5,6,7,8,9,10,11)

//12 is the first number for which greater will return true
scala> d.take(12).toList
//Returns a ton of scala.collection.immutable.Stream errors

Could someone please explain to me what exactly is going wrong here? Thanks.

4

1 回答 1

2

The code works recursively. When you run out of items in your stream, recursion gets you nowhere, and eventually you run out of stack space. (What are you expecting to happen when you ask for more items than can possibly be in your stream because you filter out all the large ones? You should either get a stack overflow or non-termination (hang), right?)

于 2013-03-30T15:48:30.223 回答