def compress[A](list: List[A]): List[(A, Int)] = { def compres21(l:List[A],x:A,acc:Int=0): Int = l match { case List() => acc case head::tail if head == x => compres21(tail,x,acc+1) case head::tail if head != x => compres21(tail,x,acc) } def reduce(l:List[A],x:A,acc:List[A]=List()) : List[A] = l match { case List() => acc.reverse case head::tail if head==x => reduce(tail,x,acc) case head::tail if head!=x => reduce(tail,x,head::acc) } def compress2(l:List[A],acc:List[(A,Int)]=List()) : List[(A,Int)] = l match { case List() => acc case head::tail => compress2(reduce(tail,head),(head,compres21(head::tail,head))::acc) } compress2(list) } println(compress(List('a','a','b','c','c','c','d','d','c')))