nil:列表[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]是什么意思?这是否意味着,我通过带有Int符号的类型传递了Nil列表?

作为 fold(和it variants)正在根据第一个参数列表确定类型参数,您不能简单地传递Nil,因为该类型将被派生为List[Nothing](您还将看到该类型第二个参数列表不匹配)。您可以使用类型的属性来告诉NilList[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

相关内容

最新更新