2013-09-21 120 views

回答

9

正如Hiura說,還是這樣的:

object ListDemo extends App { 
    val lst = List(1, 2, 3) 
    println(lst(0)) // Prints specific value. In this case 1. 
        // Number at 0 position. 
    println(lst(1)) // Prints 2. 
    println(lst(2)) // Prints 3. 
} 
9

基本上,你的Python代碼等同的:(在斯卡拉解釋器中運行)

scala> val l = 1 :: 2 :: 3 :: 4 :: Nil 
l: List[Int] = List(1, 2, 3, 4) 

scala> val one = l.head 
one: Int = 1 

scala> println(one) 
1 

Here是關於Scala的列表的文檔。


它被要求作爲附屬問題「我如何顯示每個元素?」。

這裏是一個遞歸實現使用模式匹配:

scala> def recPrint(xs: List[Int]) { 
    | xs match { 
    |  case Nil => // nothing else to do 
    |  case head :: tail => 
    |   println(head) 
    |   recPrint(tail) 
    | }} 
recPrint: (xs: List[Int])Unit 

scala> recPrint(l) 
1 
2 
3 
4 

正如大衛·韋伯在評論中指出的,如果你不能使用遞歸算法來訪問你的列表中的元素,那麼你應該考慮使用其他的容器,因爲訪問List的第i個元素需要O(N)。

+0

耶找到,但我怎麼能在列表打印第二個或第三個元素? –

+0

那麼,那是另一個問題;-) 你可以使用'apply'方法(比如在Brano88的答案中),或者在列表的尾部遞歸。 – Hiura

+3

如果您可以從頭到尾遍歷列表,然後遞歸。如果沒有,則使用錯誤的數據結構,因爲適用於O(N)的列表。改用Vector或Array。 –

2

答案可以很容易地在scaladoc for list

def head: A 
Selects the first element of this list.