【发布时间】:2021-11-05 11:16:15
【问题描述】:
我真的是语言 scala 的新手 我遇到的错误肯定和让你笑的一样简单
scala> sealed trait List[+A]
defined trait List
scala> case object Nil extends List[Nothing]
defined object Nil
scala> case class Cons[+A] (head: A, tail: List[A]) extends List[A]
defined class Cons
scala>
scala> def sum(ints: List[Int]): Int = ints match {
| case Nil => 0
| case Cons(x,xs) => x + sum(xs)
| }
<console>:28: warning: match may not be exhaustive.
It would fail on the following inputs: Cons(_, _), Nil
def sum(ints: List[Int]): Int = ints match {
^
sum: (ints: List[Int])Int
scala>
scala>
scala> def test(ints: List[Int]): Int = ints match {
| case Cons(x, Cons(2, Cons(4, _))) => x
| case Nil => 42
| case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
| case Cons(h, t) => h + sum(t)
| case _ => 101
| }
test: (ints: List[Int])Int
scala>
scala>
scala> val example3 = List(1,2,3,4,5)
example3: List[Int] = List(1, 2, 3, 4, 5)
scala>
scala>
scala> test(example3)
<console>:28: error: type mismatch;
found : scala.collection.immutable.scala.collection.immutable.List[Int]
required: List(in class $iw)[Int]
test(example3)
^
我只想知道为什么类型不匹配? def 函数测试的输出很好 --> test: (ints: List[Int])Int! 非常感谢您的回复,
【问题讨论】:
-
List(1, 2, ...)正在创建标准库List的实例,而不是您自己定义的List,这就是问题所在。首先,我建议将其重命名为MyList(和MyNil&MyCons) 以避免将来出现此类问题,其次,您需要实现自己的@987654328 @ 所以您可以使用该语法或将您的列表创建为MyCons(1, MyCons(2, MyNil))
标签: list scala function pattern-matching typeerror