Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil:List[Int] as parameter

Tags:

list

scala

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?

like image 210
softshipper Avatar asked Mar 03 '26 22:03

softshipper


1 Answers

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
like image 145
Suma Avatar answered Mar 05 '26 11:03

Suma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!