Facebook
From ja, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 124
  1. def compress[A](list: List[A]): List[(A, Int)] = {
  2.  def compres21(l:List[A],x:A,acc:Int=0): Int = l match {
  3.  
  4.   case List() => acc
  5.   case head::tail if head == x => compres21(tail,x,acc+1)
  6.   case head::tail if head != x => compres21(tail,x,acc)
  7.  
  8.  }
  9.  def reduce(l:List[A],x:A,acc:List[A]=List()) : List[A] = l match {
  10.  
  11.   case List() => acc.reverse
  12.   case head::tail if head==x => reduce(tail,x,acc)
  13.   case head::tail if head!=x => reduce(tail,x,head::acc)
  14.  
  15.  }
  16.  def compress2(l:List[A],acc:List[(A,Int)]=List()) : List[(A,Int)] = l match {
  17.   case List() => acc
  18.   case head::tail => compress2(reduce(tail,head),(head,compres21(head::tail,head))::acc)
  19.  }
  20.  compress2(list)
  21. }
  22.  
  23. println(compress(List('a','a','b','c','c','c','d','d','c')))