与 trait 相关的书中的 Scala 示例
Scala example from a book related to trait
我正在尝试运行上面的例子。但它失败了。有人可以帮忙吗。我想我缺少一些非常基本的东西。
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
def product(ds: List[Double]): Double = ds match {
case Nil => 1.0
case Cons(0.0, _) => 0.0
case Cons(x,xs) => x * product(xs)
}
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
}
ERROR
*scala> val x = (1 to 10).toList
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)*
*scala> List.sum(x)
<console>:19: error: type mismatch;
found : scala.collection.immutable.List[Int]
required: List(in object $iw)[Int]
List.sum(x)*
^
这是书中的一个例子。我尝试了 make List[Int] 但仍然是同样的错误。
使用您定义的 Cons
和 Nil
案例 类 创建一个 List
。
scala> Cons(0, Cons(1, Cons(2, Nil)))
res4: Cons[Int] = Cons(0,Cons(1,Cons(2,Nil)))
scala> List.sum(res4)
res5: Int = 3
您(和编译器)对您定义的 List
对象和标准库提供的 List
感到困惑。当他们同名时很容易犯的错误。
Range
对象(1 到 10)的 toList
方法 returns 库 List
但您的代码想要处理它自己的 List
键入,而不是图书馆的。
您可以像这样创建适当类型的列表(即您的列表):
val x: List[Int] = List(1,2,3,4)
我正在尝试运行上面的例子。但它失败了。有人可以帮忙吗。我想我缺少一些非常基本的东西。
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
def product(ds: List[Double]): Double = ds match {
case Nil => 1.0
case Cons(0.0, _) => 0.0
case Cons(x,xs) => x * product(xs)
}
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
}
ERROR
*scala> val x = (1 to 10).toList
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)*
*scala> List.sum(x)
<console>:19: error: type mismatch;
found : scala.collection.immutable.List[Int]
required: List(in object $iw)[Int]
List.sum(x)*
^
这是书中的一个例子。我尝试了 make List[Int] 但仍然是同样的错误。
使用您定义的 Cons
和 Nil
案例 类 创建一个 List
。
scala> Cons(0, Cons(1, Cons(2, Nil)))
res4: Cons[Int] = Cons(0,Cons(1,Cons(2,Nil)))
scala> List.sum(res4)
res5: Int = 3
您(和编译器)对您定义的 List
对象和标准库提供的 List
感到困惑。当他们同名时很容易犯的错误。
Range
对象(1 到 10)的 toList
方法 returns 库 List
但您的代码想要处理它自己的 List
键入,而不是图书馆的。
您可以像这样创建适当类型的列表(即您的列表):
val x: List[Int] = List(1,2,3,4)