当类型为 A 时默认设置什么(Scala)
What to set as default when the type is A (Scala)
我有一个 Scala 练习,我必须将那种列表 (a,a,a,b,c,d,d,e,a,a) 转换为
((a,3),(b,1),(c,1),(d,2),(e,1),(a,2))。
我显然知道我的算法还不正确,但我想从任何事情开始。
问题是我不知道如何打开该功能(最后一行),因为错误是无论我将其作为先前的参数,它都表示需要:A,找到:Int/String 等。
previous本意是作为上一次迭代的head。
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, acc :+ (head, counter), head, 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, (a, n+1) :: rest)
case (head :: tail, _) => compress (tail, (head, 1) :: acc)
}
我有一个 Scala 练习,我必须将那种列表 (a,a,a,b,c,d,d,e,a,a) 转换为 ((a,3),(b,1),(c,1),(d,2),(e,1),(a,2))。 我显然知道我的算法还不正确,但我想从任何事情开始。 问题是我不知道如何打开该功能(最后一行),因为错误是无论我将其作为先前的参数,它都表示需要:A,找到:Int/String 等。 previous本意是作为上一次迭代的head。
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, acc :+ (head, counter), head, 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, (a, n+1) :: rest)
case (head :: tail, _) => compress (tail, (head, 1) :: acc)
}