Can I do a lazy take with a long parameter?

偶尔善良 提交于 2019-12-12 05:41:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!