2016-01-24 59 views
0

我试图运行上面的例子。但它失败了。有人可以帮忙吗?我想我错过了一些非常基本的东西。Scala相关特征的例子

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)* 
       ^

以书为例。我尝试通过使List [Int]但仍然相同的错误。

回答

1

你(和编译器)感到困惑,您已经定义的List对象,标准库提供的List之间。当他们都有相同的名字时容易犯错。

Range对象(1〜10)的toList方法返回一个库List但你的代码要处理自己的List类型,而不是图书馆。

您可以创建列表像这样适当类型(即你的列表):

val x: List[Int] = List(1,2,3,4) 
1

使用您定义的ConsNil个案类创建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