代码之家  ›  专栏  ›  技术社区  ›  acjay Sreekanth

在Scala中使用偏移量编写泛型takeWhile

  •  2
  • acjay Sreekanth  · 技术社区  · 7 年前

    takeWhile

    def takeWhileWithOffset[A, Iter[_] <: Iterable[A]](iter: Iter[A], p: A => Boolean, offset: Int)
    

    Iterable 作为约束,因为希望它与 Stream . 但我很难想出如何使这项工作成功。如果我使用一个严格的集合,我可以使用 dropRight 如果偏移量不是正的。但是 可迭代的 右下角

    积极的案例更为棘手。我可以用 sliding 有效抓取未来物品,然后使用 init lastOption 之后 takeWhile公司 终止。但是 没有 最后一个选项 .

    只有 这个 takeWhile公司 终止。有办法做到这一点吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   som-snytt    7 年前

    span take :

    scala> val it = (1 to 100).iterator
    it: Iterator[Int] = non-empty iterator                              
    
    scala> val (a, b) = it.span(_ < 10)
    a: Iterator[Int] = non-empty iterator
    b: Iterator[Int] = unknown-if-empty iterator
    
    scala> val res = a ++ b.take(5)
    res: Iterator[Int] = non-empty iterator
    
    scala> res.toList
    res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)