2017-03-15 7 views
2

として一覧[INT]私は、次のしている特性の定義:無記号:パラメータ

sealed trait List[+A] 

// `List` data type, parameterized on a type, `A` 
case object Nil extends List[Nothing] 

// A `List` data constructor representing the empty list 
/* Another data constructor, representing nonempty lists. Note that `tail` is another `List[A]`, 
which may be `Nil` or another `Cons`. 
*/ 
case class Cons[+A](head: A, tail: List[A]) extends List[A] 

と機能:

def add1(l: List[Int]): List[Int] = 
    foldRight(l, Nil:List[Int])((h,t) => Cons(h+1,t)) 

私の質問は、Nil:List[Int]は何を意味していますか?つまり、表記のタイプのNilリストを渡しますか? foldとして

+2

ここでは、 '' List.empty [INT]と同じです – dveim

答えて

2

は(それは変異体)最初のパラメータリストに基づいて、タイプパラメータを決定されたタイプがList[Nothing]のように導出されるように、単に、Nilを渡すことができない(あなたはまた、第2のパラメータリストが一致しない参照であろう)。 type ascriptionを使用してNilのタイプがList[Int]であることを伝えることができます。また、型パラメータとしてList[Int]を渡すことができます。

foldRight[List[Int]](l, Nil)((h,t) => Cons(h+1,t)) 

参考のため、foldRight署名はこれです:

def foldRight[B](z: B)(op: (A, B) => B): B 
関連する問題