Do you want this to be fast to run or fast to code?
Let's say we have
val ns = Array(0.1, 0.2, 0.3, 0.4, 0.5)
val tf = Array(true, true, false, false, true)
If you want it to be fast to run, it's a bit of work, as you've already shown:
def chopsum(ns: Array[Double], tf: Array[Boolean]) = {
var i = 0
var n = 0
val L = math.min(ns.length, tf.length)
while (i < L) {
if (tf(i)) n += 1
i += 1
}
if (!tf(L-1)) n += 1
val result = new Array[Double](n)
var i = 0
var n = 0
while (i < L) {
result(n) += ns(i)
if (tf(i)) n += 1
i += 1
}
result
If you want your code to be compact, you can, for instance,
def chopsum(xs: Seq[(Double, Boolean)], answer: Vector[Double] = Vector()): Vector[Double] = {
if (xs.isEmpty) answer
else {
val (pre, post) = xs.span(! _._2)
chopsum(post.drop(1), answer :+ (pre ++ post.take(1)).map(_._1).sum)
}
}
chopsum(ns zip ts)
This is about the best you can do, given that Scala doesn't have a chop-into-groups method. I have one on StackOverflow at
http://stackoverflow.com/questions/5410846 as my example of adding a method to collections. Using that (the version that works with arrays), one could simply
(ns zip tf).groupedWhile((x,_) => !x._2).map(_.map(_._1).sum)
which illustrates why such a method was sufficiently heavily asked-for that I used it as my example.
--Rex