问题
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?
回答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)
}
}
来源:https://stackoverflow.com/questions/28883876/can-i-do-a-lazy-take-with-a-long-parameter