If you don't mind adding some infrastructure to handle the groupedWhile function, you can steal from Rex Kerr the answer to the scala collection extension . Use the section that processes the array in the second part of the answer.
Then this is 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 is based on using Iterator.iterate , which starts with a seed and re-uses the span function to retrieve the next group of elements that have the same logical property. In this case, the seed is a tuple of the following group, and the rest is processed:
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 the span for empty arrays does not raise a predicate, so we don't get an exception on rest.head if the remainder is empty.
source share