【发布时间】:2016-11-04 10:39:49
【问题描述】:
我是 Scala 新手。作为一个练习,我试图在一个带有警卫的元组列表上编写一个匹配语句。我知道地图可以解决问题,但我正在尝试了解模式匹配。
我试图编写一个以List[(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。
有什么建议吗?
【问题讨论】:
-
查看错误消息:您正在匹配
chars,这是一个List[(Char,Int)],但在您希望x是List[(String, Int)]的模式中。
标签: scala pattern-matching pattern-guards