Here's my take using foldLeft:
def compress(s: String) = {
val a : List[(Char,Int)] = List()
s.toCharArray.foldLeft(a)((acc, elem) => acc match {
case Nil => (elem, 1) :: Nil
case head(a, b) :: tail =>
if (head._1a == elem) (elem, head._2b + 1) :: tail else (elem, 1) :: acc
}).reverse
.map{ case (ea, b) => e._1a.toString + e._2)b }
.mkString("")
}
Note: I have assumed that order matters. That is, aabbbaa
will reduce to a2b3a2