type Occurrences = List[(Char, Int)]
val lard = List(('a', 1), ('d', 1), ('l', 1), ('r', 1))
val r = List(('r', 1))
def subtract2(x: Occurrences, y: Occurrences): Occurrences =
x.foldLeft(List[(Char, Int)]())({case (acc, list) if(!(y.contains(list))) => acc.::(list)})
subtract2(lard, r)
引发
scala.MatchError: (List(),(a,1)) (of class scala.Tuple2)
at forcomp.A$A183$A$A183$$anonfun$subtract2$1.apply(temp.sc:11)
at forcomp.A$A183$A$A183$$anonfun$subtract2$1.apply(temp.sc:11)
at scala.collection.LinearSeqOptimized$class.foldLeft(temp.sc:120)
at scala.collection.immutable.List.foldLeft(temp.sc:80)
at forcomp.A$A183$A$A183.subtract2(temp.sc:11)
at #worksheet#.#worksheet#(temp.sc:14)
这个错误的原因是什么?我想,所有问题都有缺点,但更确切地说我不知道
答案 0 :(得分:6)
只要对象与模式匹配表达式的任何模式都不匹配,就会抛出MatchError。
通常foldLeft
期望一个完全定义的函数,你给它的是partially defined函数。在这种情况下,左折的参数应该有两种情况:
答案 1 :(得分:4)
您收到匹配错误,因为您没有涵盖所有情况(例如,当y.contains(列表)时)
def subtract2(x: Occurrences, y: Occurrences): Occurrences =
x.foldLeft(List[(Char, Int)]()) ({
case (acc, list) if !(y.contains(list)) => acc.::(list)
case (acc,list) => acc})
答案 2 :(得分:-1)
试试这个
val lard = List(('a', 1), ('d', 1), ('l', 1), ('r', 1))
val r = List(('r', 1))
lard diff r
答案 3 :(得分:-1)
我认为这是因为你没有在foldLeft
方法中指定开始和其余部分。如果不指定start
元素和rest
,它将始终附加空列表List()
并且模式匹配失败(就像在错误日志(List(),(a,1))
中一样)。添加另一个匹配方案将解决MatchError
,但可能会产生与您想象的结果不同的结果。
尝试类似的东西:
def subtract2(x: Occurrences, y: Occurrences): Occurrences =
x.foldLeft(List[(Char, Int)]){ (start, rest) =>
start match {
case (acc, list) => if !(y.contains(list)) => acc.::(rest)
case _ => handle_other_cases_here
}
}