当类型为 A (Scala) 时将什么设置为默认值

问题描述

我在 Scala 中有一个练习,我必须将那种列表 (a,a,b,c,d,e,a) 转换为 ((a,3),(b,1),(c,(d,2),(e,(a,2))。 我显然知道我的算法还不正确,但我想从任何事情开始。 问题是我不知道如何打开该函数(最后一行),因为错误是无论我将其作为先前的参数,它都表示需要:A,找到:Int/String 等。 前一个是作为前一个迭代的负责人。

def compress[A](l: List[A]): List[(A,Int)] = {
  def compressHelper(l: List[A],acc: List[(A,Int)],prevIoUs: A,counter: Int): List[(A,Int)] = {
    l match {
      case head::tail => {
        if (head == prevIoUs) {
          compressHelper(tail,acc :+ (head,counter+1),head,counter+1)
        }
        else {
          compressHelper(tail,counter),1)
        }
      }
      case Nil => acc
    }
  }
  compressHelper(l,List(),1)
}

解决方法

您不需要显式传递 previous,只需查看累加器:

def compress[A](l: List[A],acc: List[(A,Int)]=Nil): List[(A,Int)] =
   (l,acc) match {
       case (Nil,_) => acc.reverse
       case (head :: tail,(a,n) :: rest) if a == head =>
            compress(tail,n+1) :: rest)
       case (head :: tail,_) => compress (tail,(head,1) :: acc)
}