If you don't mind adding some infrastructure to handle a groupedWhile
feature, you can steal from Rex Kerr's answer on extending scala collection. Use the section that handles array, in the second part of the answer.
Then it's a breeze:
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))
Edit:
I came up with a solution that does not require groupedWhile
. It's based on using Iterator.iterate
which starts from a seed and repeatedly applies the span
function to extract the next group of elements that have the same boolean property. In this instance the seed is a tuple of the next group and the remainder to process:
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
Which prints the same result as above. Note that span
for empty arrays does not call the predicate, so we don't get an exception on rest.head
if rest is empty.