閱讀336 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Coursera Scala 4-7:Lists


Coursera Scala 4-7:Lists

Lists

val nums = List(1,3,4)
val empty = List()
val fruit = List("apples","oranges")
val diag3 = List(List(1,0,0),List(0,1,0),List0,0,1))
  • immutable
  • List是遞歸的,arrays則不是

The List Type

和arrays一樣,lists的元素必須是相同類型的。

Constructors of Lists

所有的Lists由:

  • 空的list Nil
  • 構造操作::,舉個例子x :: xs會創建新的list,第一個元素為x,第二個元素為xs

Right Associativity

::是右結合性

"1"::("2"::("3"::Nil))            //> res1: List[String] = List(1, 2, 3)

scala中做了簡化 所以 也可以寫成

"1"::"2"::"3"::Nil

是等價的 ,::其實是方法名 相當於調用方法 可以寫成.::

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

Operations on Lists

  • head 取第一個元素
  • tail 返回不包含第一個元素的list
  • isEmpty

更多用於List的函數:

  • xs.length
  • xs.last 獲得最後一個
  • xs.init 得到一個除了最後一個元素的列表
  • xs take n
  • xs drop n
  • xs(n)

Console代碼

scala> def xs= List(0,1,2,3,4)  
xs: List[Int]  

scala> xs.length  
res0: Int = 5  

scala> xs.last  
res1: Int = 4  

scala> xs.init  
res2: List[Int] = List(0, 1, 2, 3)  

scala> xs take 1  
res3: List[Int] = List(0)  

scala> xs drop 1  
res4: List[Int] = List(1, 2, 3, 4)  

scala> xs(0)  
res5: Int = 0

創建新列表:
xs ++ ys 合並
xs.reverse 倒序
xs.updated(n,x)

查找元素:
xs indexOf x 不存在返回-1
xs contains x

List Patterns

Nil 表示空list
p :: ps 表示以p開頭的元素 這個模式和[Head|Tail]一致
List(p1,...,p2) 也可以寫成 p1::....::pn::Nil
當然也可以用_
例子:

   List(1,2,3) match {
      case List(1,_,3) => "yes"  //這樣其實也是一種構造模式吧
   }                                              //> res2: String = yes

最後更新:2017-04-03 05:39:17

  上一篇:go Coursera Scala 2-5,6:類
  下一篇:go Android中自定義樣式與View的構造函數中的第三個參數defStyle的意義