scala> val xs = List(0,5,34,0,9,0,0,0) xs: List[Int] = List(0, 5, 34, 0, 9, 0, 0, 0) scala> xs.reverse.dropWhile(_ == 0).reverse res1: List[Int] = List(0, 5, 34, 0, 9)
EDIT:
Here's a one-pass (O (n)) way that adds an implicit dropWhileRight
method to Seq
class EnhancedSeq[A, Repr <: Seq[A]](seq: SeqLike[A, Repr]) { def dropRightWhile[That](p: A => Boolean)(implicit bf: CanBuildFrom[Repr, A, That]): That = { val b = bf(seq.asInstanceOf[Repr]) val buffer = collection.mutable.Buffer[A]() for (x <- seq) { buffer += x if (!p(x)) { b ++= buffer buffer.clear() } } b.result } } implicit def enhanceSeq[A, Repr <: Seq[A]](seq: SeqLike[A, Repr]) = new EnhancedSeq(seq)
And you just use it like this:
scala> List(0,5,34,0,9,0,0,0).dropRightWhile(_ == 0) res2: List[Int] = List(0, 5, 34, 0, 9)