I have following trait definition:
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]
and a function:
def add1(l: List[Int]): List[Int] =
foldRight(l, Nil:List[Int])((h,t) => Cons(h+1,t))
My question is, what does Nil:List[Int] mean? Does it mean, I pass a Nil list with type with Int notation?
As fold (and it variants) is determining the type parameter based on the first parameter list, you cannot simply pass Nil, as the type would be derived as List[Nothing] (you would also see the second parameter list not matching). You can use type ascription to tell the Nil is of type List[Int]. You could also pass the List[Int] as the type parameter:
foldRight[List[Int]](l, Nil)((h,t) => Cons(h+1,t))
For the reference, foldRight signature is this:
def foldRight[B](z: B)(op: (A, B) => B): B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With