列表(List)應(yīng)該是使用最多的數(shù)據(jù)結(jié)構(gòu)了认臊。
列表的構(gòu)造
注意列表中的元素類型必須一致锄奢。
val fruit = List("apples", "oranges", "pears")
val nums: List[Int] = List(1, 2, 3, 4)
構(gòu)造列表的兩個(gè)基本單位是Nil
和::
。上面的構(gòu)造可以寫(xiě)成
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
val nums =1::(2::(3::(4::Nil)))
理解這一點(diǎn)對(duì)列表的操作和模式匹配很有幫助涂屁。
列表操作
Scala列表有三個(gè)基本操作:
-
head
返回列表第一個(gè)元素 -
tail
返回一個(gè)列表灰伟,包含除了第一元素之外的其他元素 -
isEmpty
在列表為空時(shí)返回true
對(duì)于Scala列表的任何操作都可以使用這三個(gè)基本操作來(lái)表達(dá)。比如插入排序算法就可以這樣實(shí)現(xiàn)帖族。
def isort(xs: List[Int]): List[Int] =
if (xs.isEmpty) Nil
else insert(xs.head, isort(xs.tail))
def insert(x: Int, xs: List[Int]): List[Int] =
if (xs.isEmpty || x <= xs.head) x :: xs
else xs.head :: insert(x, xs.tail)
列表的模式
使用前面提到的模式匹配发笔,可以使插入排序算法更加直觀。
def isort(xs: List[Int]): List[Int] = xs match {
case List() => List()
case x :: xs1 => insert(x, isort(xs1))
}
def insert(x: Int, xs: List[Int]): List[Int] = xs match {
case List() => List(x)
case y :: ys => if (x <= y) x :: xs
}
列表的常用操作
下面的代碼列舉了Scala List的常用操作了讨。
scala> List(1, 2) ::: List(3, 4, 5) // 連接兩個(gè)列表
res0: List[Int] = List(1, 2, 3, 4, 5)
scala> List(1, 2, 3).length //length
res3: Int = 3
// last and init
val abcde = List('a', 'b', 'c', 'd', 'e')
scala> abcde.last
res4: Char = e
scala> abcde.init
res5: List[Char] = List(a, b, c, d)
abcde.reverse
res6: List[Char] = List(e, d, c, b, a)
// take, drop and splitAt
scala> abcde take 2
res8: List[Char] = List(a, b)
scala> abcde drop 2
res9: List[Char] = List(c, d, e)
scala> abcde splitAt 2
res10: (List[Char], List[Char]) = (List(a, b),List(c, d, e))
// flatten
scala> List(List(1, 2), List(3), List(), List(4, 5)).flatten
res14: List[Int] = List(1, 2, 3, 4, 5)
// zip and unzip
scala> abcde.indices zip abcde
res17: scala.collection.immutable.IndexedSeq[(Int, Char)] =
IndexedSeq((0,a), (1,b), (2,c), (3,d), (4,e))
scala> abcde.zipWithIndex
res18: List[(Char, Int)] = List((a,0), (b,1), (c,2), (d,3),
(e,4))
scala> zipped.unzip
res19: (List[Char], List[Int]) = (List(a, b, c),List(1, 2, 3))
// toString and mkString
scala> abcde.toString
res20: String = List(a, b, c, d, e)
scala> abcde mkString ("[", ",", "]")
res21: String = [a,b,c,d,e]
列表的常用高階方法
高階方法是指包含函數(shù)作為參數(shù)的方法前计。這些方法是Scala作為一個(gè)函數(shù)式語(yǔ)言所特有的男杈,能夠方便的實(shí)現(xiàn)列表的轉(zhuǎn)變(Trasnformation)。最近Java8也引入了類似的方法集合伶棒。
map肤无, flatmap
xs map f
就是將函數(shù)f作用于List xs中的每個(gè)元素,返回一個(gè)新的List宛渐。比如:
scala> List(1, 2, 3) map (_ + 1)
res32: List[Int] = List(2, 3, 4)
scala> val words = List("the", "quick", "brown", "fox")
words: List[java.lang.String] = List(the, quick, brown, fox)
scala> words map (_.length)
res33: List[Int] = List(3, 5, 5, 3)
scala> words map (_.toList.reverse.mkString)
res34: List[String] = List(eht, kciuq, nworb, xof)
flatmap和map十分相似,唯一的區(qū)別就是返回時(shí)會(huì)把所用列表中的元素連起來(lái)鳞仙,生成一個(gè)扁平的列表笔时。下面的例子比較了map和flatmap。
scala> words map (_.toList)
res35: List[List[Char]] = List(List(t, h, e), List(q, u, i,
c, k), List(b, r, o, w, n), List(f, o, x))
scala> words flatMap (_.toList)
res36: List[Char] = List(t, h, e, q, u, i, c, k, b, r, o, w,
n, f, o, x)
filter
xs filter p梳玫,返回一個(gè)列表右犹,包含xs中滿足predicate p的元素。比如:
scala> List(1, 2, 3, 4, 5) filter (_ % 2 == 0) res40: List[Int] = List(2, 4)
fold
另外一類常用的列表操作是將某種操作以某種累計(jì)的形式作用于列表中的元素盼忌。這就是fold掂墓。通常又分為foldLeft
和foldRight
,只是執(zhí)行順序不同。比如:
scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n)
res0: Int = 55
這里0為初始值(記住numbers是List[Int]類型)跨嘉,m作為一個(gè)累加器吃嘿。從1加到10。如果使用foldRight
那就是從10加到1兑燥。
此外降瞳,還有很多高階方法比如range
, fill
,sortWith
等等挣饥,不再贅述扔枫。