2016-01-24 90 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