如果您不介意添加一些基础架构来处理 groupedWhile 功能,您可以从 Rex Kerr 的 answer on extending scala collection 中窃取信息。在答案的第二部分使用处理数组的部分。
那就轻而易举:
scala> vals.groupedWhile(_._2 == _._2).filter(_.head._2 == true).map{g =>
(g.head, g.last)}.foreach(println)
((0,true),(3,true))
((5,true),(6,true))
((8,true),(9,true))
编辑:
我想出了一个不需要groupedWhile 的解决方案。它基于使用Iterator.iterate,它从种子开始并重复应用span 函数来提取具有相同布尔属性的下一组元素。在这种情况下,种子是下一组的元组和要处理的剩余部分:
type Arr = Array[(Int, Boolean)] // type alias for easier reading
val res = Iterator.iterate[(Arr, Arr)]((Array(), vals)){ case (same, rest) =>
// repeatedly split in (same by boolean, rest of data)
// by using span and comparing against head
rest.span(elem => elem._2 == rest.head._2)
}.drop(1).takeWhile{ case (same, _) => // drop initial empty seed array
same.nonEmpty // stop when same becomes empty
}.collect{ case (same, _) if same.head._2 == true =>
// keep "true" groups and extract (first, last)
(same.head, same.last)
}.foreach(println) // print result
打印与上面相同的结果。请注意,空数组的 span 不会调用谓词,因此如果 rest 为空,我们不会在 rest.head 上得到异常。