Scala基礎(chǔ)(9)- 列表

列表(List)應(yīng)該是使用最多的數(shù)據(jù)結(jié)構(gòu)了。

列表的構(gòu)造

注意列表中的元素類(lèi)型必須一致。

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)

列表的模式

使用前面提到的模式匹配,可以使插入排序算法更加直觀(guān)。

 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也引入了類(lèi)似的方法集合。

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中滿(mǎn)足predicate p的元素。比如:

scala> List(1, 2, 3, 4, 5) filter (_ % 2 == 0) res40: List[Int] = List(2, 4)

fold

另外一類(lèi)常用的列表操作是將某種操作以某種累計(jì)的形式作用于列表中的元素。這就是fold。通常又分為foldLeftfoldRight,只是執(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]類(lèi)型),m作為一個(gè)累加器。從1加到10。如果使用foldRight那就是從10加到1。

此外,還有很多高階方法比如range, fill,sortWith等等,不再贅述。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容