Why is Nil required at the end of a list built using the cons operator

前端 未结 3 790
一个人的身影
一个人的身影 2020-12-06 20:50

I\'m learning Scala at the moment (Programming Scala, 2nd Edition, Odersky).

When building a list using the cons operator we have to write:

val l = 1         


        
相关标签:
3条回答
  • 2020-12-06 21:33

    The signature of :: is roughly:

    case class ::[E](hd: E, tl: List[E]) extends List[E]
    
    // which generates this automatically:
    
    object :: {
        def apply[E](hd: E, tl: List[E]): ::[E]
    }
    

    The signature of Nil is roughly:

    object Nil extends List[Nothing]
    

    As you see, :: takes an element and a list. 4 is not a list, while Nil is.

    0 讨论(0)
  • 2020-12-06 21:33

    In concept, a List in Scala is either

    • a Nil (means an empty list) or
    • a head element and tail, which is a List again.

    :: is to create a new list with a head element and a tail list. And it is right associative.

    So

    1 :: 2 :: 3 :: 4 :: Nil 
    

    will be compiled as

    1 :: (2 :: (3 :: (4 :: Nil)))
    

    Starting from the right, the first list is constructed with 4 and Nil, making a new list [4]. Then adding 3 as the head of the tail list [4], making a new list [3, 4]. And so on...

    To answer your question, Scala needs an empty list to construct the 1st list. Cause that's how the list is defined in Scala.

    0 讨论(0)
  • 2020-12-06 21:49

    Actually, you can make it work yourself:

    scala> implicit class Listable[A](val value: A) {
         |   def ::[B >: A](other: B): List[B] = other :: value :: Nil
         | }
    defined class Listable
    
    scala> val xs = 1 :: 2 :: 3 :: 4
    xs: List[Int] = List(1, 2, 3, 4)
    
    scala> val ys = "A" :: "B" :: "C"
    ys: List[String] = List(A, B, C)
    
    scala>
    
    0 讨论(0)
提交回复
热议问题