2
我正在學習Scala(編程Scala,第2版,Odersky)。爲什麼Nil需要在使用cons運算符構建的列表末尾
當使用利弊運營商,我們必須寫建立一個列表:
val l = 1 :: 2 :: 3 :: 4 :: Nil
爲什麼我們需要一個無在結束了嗎?爲什麼不能編譯器明白,4是最後一個元素,所以只寫這個:
val l = 1 :: 2 :: 3 :: 4
我正在學習Scala(編程Scala,第2版,Odersky)。爲什麼Nil需要在使用cons運算符構建的列表末尾
當使用利弊運營商,我們必須寫建立一個列表:
val l = 1 :: 2 :: 3 :: 4 :: Nil
爲什麼我們需要一個無在結束了嗎?爲什麼不能編譯器明白,4是最後一個元素,所以只寫這個:
val l = 1 :: 2 :: 3 :: 4
的::
簽名大致是:
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]
}
的Nil
簽名大致是:
object Nil extends List[Nothing]
如您所見,::
需要一個元素和一個列表。 4
不是一個列表,而Nil
是。
其實,你可以讓它工作你自己:
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>
所以必須建立開始4 ::無列表,3 ::(4 ::無)等? –
正確。以冒號(:)開頭的操作符在Scala中是正確的關聯,基本上支持這個用例。 –
我認爲這個答案在提及'::'case類時很混亂。這是與問題相關的'::'方法。 –