我是 Scala 新手。作为一个练习,我试图在一个带有警卫的元组列表上编写一个匹配语句。我知道地图可以解决问题,但我正试图了解模式匹配。
我试图编写一个以 aList[(Char, Int)]
作为参数的函数。该函数对条目进行排序,如果两个条目具有相同的键值,则将它们相加。所以下面的论点List(('q', 1'), ('a', 1), ('c', 2), ('a', 2), ('c', 1))
会变成List(('a', 3), ('c', 3'), ('q', 1))
。
我附带以下代码:
def sortAndAggregateList(chars: List[(Char, Int)]) : List[(Char, Int)] = {
chars match {
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 > charP2) =>
sortAndAggregateList((charP2, numP2) :: (charP1, numP1) :: x)
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 < charP2) =>
sortAndAggregateList((charP1, numP1) :: (charP2, numP2) :: x)
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 == charP2) =>
sortAndAggregateList((charP1, numP1 + numP2) :: x)
case Nil =>
Nil
}
}
但我收到以下警告:
:14:警告:没有结果的类型测试:List[(Char, Int)] 类型的值也不能是 List[(String, Int)] (List[(String, Int)] 的基础)(但仍然可能匹配它的擦除)
我尝试删除列表,但如果这样做,我会收到一个x
类型为的错误Any
。
有什么建议么?