0

Stream.take takes an int as a parameter. I want to define a take that takes a long instead- is this possible without using takeWhile to manage a counter?

lsankar4033
  • 509
  • 3
  • 14
  • So long as you don't keep any reference to the head while you're iterating over the stream, that's correct. But if that's the case then maybe you'd be better off just using an `Iterator`(and if you want your code to be more generic, just work on a `TraversableOnce`, which `Iterator` extends). – Régis Jean-Gilles Mar 05 '15 at 17:51
  • I'm going with takeWhile with a counter for now. It's a trivial amount of memory (counter) to manage myself, just figured the main collections lib would support it – lsankar4033 Mar 05 '15 at 17:58

1 Answers1

1

Just so you know that it's at least doable (but is it a good idea?), you can enrich Stream with an alternate version of take:

implicit class StreamOps[A](val stream: Stream[A]) extends AnyVal {
  def take(n: Long): Stream[A] = {
    if (n <= 0 || stream.isEmpty) Stream.empty
    else if (n == 1) Stream.cons(stream.head, Stream.empty)
    else Stream.cons(stream.head, stream.tail take n-1)
  }
}
Régis Jean-Gilles
  • 32,541
  • 5
  • 83
  • 97