Given a Scala sequence...
val sequence: Seq = List( 3, 1, 4, 1, 5, 9, 2, 6, 5 )
...say that I want to find all subsequences matching certain criteria, e.g. strings of odd numbers, and replace those with the result of some operation on that subsequence, say its length, producing a new sequence:
val sequence2: Seq = List( 2, 4, 3, 2, 6, 1 )
(Yes, this is a fairly contrived example, but it's concise.)
So far the best I've been able to do is this ugly imperative hack:
val sequence: Seq[Int] = List( 3, 1, 4, 1, 5, 9, 2, 6, 5 )
var sequence2 = List[Int]() // this is going to be our result
var subsequence = List[Int]()
for (s <- sequence) {
if (s % 2 == 0) {
if (!subsequence.isEmpty) {
sequence2 = sequence2 :+ subsequence.length
subsequence = List[Int]()
}
sequence2 = sequence2 :+ s
} else {
subsequence = subsequence :+ s
}
}
if (!subsequence.isEmpty) {
sequence2 = sequence2 :+ subsequence.length
}
Is there an elegant (/ functional) way to do this?