Compressing string in Scala, how to do this immutably?
Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) =&gt; acc match {
        case Nil =&gt; (elem, 1) :: Nil
        case (a, b) :: tail =&gt;
            if (a == elem) (elem, b + 1) :: tail else (elem, 1) :: acc
    }).reverse
    .map{ case (a, b) =&gt; a.toString + b }
    .mkString("")
}


Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2