match.error的原因是什么?

Evg*_*niy 0 scala pattern-matching

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)
Run Code Online (Sandbox Code Playgroud)

抛出

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)
Run Code Online (Sandbox Code Playgroud)

这个错误的原因是什么?我想,所有问题都有缺点,但更确切地说我不知道

Den*_*sca 6

MatchError只要对象不匹配的图案匹配表达的任何图案被抛出.

通常foldLeft期望一个完全定义的函数,你给它的是一个部分定义的函数.在这种情况下,您向左折叠的参数应该有两种情况:

  1. case(acc,list)if(!(y.contains(list))
  2. case(acc,list)if(y.contains(list))