Larry OBrien
Larry OBrien

Reputation: 8606

How to start a Scala stream some distance "in" (ala takeWhile)?

The question Why does my takeWhile fail to work with my Stream makes it clear that takeWhile() is lazy:

Stream.from(1).takeWhile(_ < 5) //Stream(1, ?) 

But for that question the solution seemed to be that one could use toList to force evaluation as desired. But what if you want, not a list or specific value, but the continuing Stream?

It would seem that I could do it by forcing evaluation until I found the desired value and then instantiate the Stream again and use index but surely there's a better way?

UPDATE: Apparently my phrasing was confusing; I wanted the solution provided by dropWhile.

Upvotes: 2

Views: 472

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

It's very difficult to understand what you are asking for -- as can be seen by everyone answering a different thing. Here's the answer to another possible interpretation: you want the stream starting at a value. Well, in this case, you can do this:

scala> Stream.from(1).dropWhile(_ < 5) //Stream(1, ?) 
res3: scala.collection.immutable.Stream[Int] = Stream(5, ?)

Upvotes: 0

Travis Brown
Travis Brown

Reputation: 139038

You can use span:

scala> val (before, after) = Stream.from(1).span(_ < 5)
before: scala.collection.immutable.Stream[Int] = Stream(1, ?)
after: scala.collection.immutable.Stream[Int] = Stream(5, ?)

Or, if you only care about "the continuing stream", dropWhile:

scala> val after = Stream.from(1).dropWhile(_ < 5)
after: scala.collection.immutable.Stream[Int] = Stream(5, ?)

Upvotes: 7

kiritsuku
kiritsuku

Reputation: 53348

It seems you are looking for force:

scala> val s = Stream.from(1).takeWhile(_<10)
s: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> s.force
res84: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, 5, 6, 7, 8, 9)

Upvotes: 1

Related Questions