<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                課程內容: [TOC=1,2] # 基本數據結構 Scala提供了一些不錯的集合。 **參考**?Effective Scala 對怎樣使用?[集合](http://twitter.github.com/effectivescala/#Collections)的觀點。 ## 列表 List ~~~ scala> val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) ~~~ ## 集 Set 集沒有重復 ~~~ scala> Set(1, 1, 2) res0: scala.collection.immutable.Set[Int] = Set(1, 2) ~~~ ## 元組 Tuple 元組是在不使用類的前提下,將元素組合起來形成簡單的邏輯集合。 ~~~ scala> val hostPort = ("localhost", 80) hostPort: (String, Int) = (localhost, 80) ~~~ 與樣本類不同,元組不能通過名稱獲取字段,而是使用位置下標來讀取對象;而且這個下標基于1,而不是基于0。 ~~~ scala> hostPort._1 res0: String = localhost scala> hostPort._2 res1: Int = 80 ~~~ 元組可以很好得與模式匹配相結合。 ~~~ hostPort match { case ("localhost", port) => ... case (host, port) => ... } ~~~ 在創建兩個元素的元組時,可以使用特殊語法:`->` ~~~ scala> 1 -> 2 res0: (Int, Int) = (1,2) ~~~ **參考**?Effective Scala 對?[解構綁定](http://twitter.github.com/effectivescala/#Functional programming-Destructuring bindings)?(“拆解”一個元組)的觀點。 ## 映射 Map 它可以持有基本數據類型。 ~~~ Map(1 -> 2) Map("foo" -> "bar") ~~~ 這看起來像是特殊的語法,不過不要忘了上文討論的`->`可以用來創建二元組。 Map()方法也使用了從第一節課學到的變參列表:`Map(1 -> "one", 2 -> "two")`將變為?`Map((1, "one"), (2, "two"))`,其中第一個參數是映射的鍵,第二個參數是映射的值。 映射的值可以是映射甚或是函數。 ~~~ Map(1 -> Map("foo" -> "bar")) ~~~ ~~~ Map("timesTwo" -> { timesTwo(_) }) ~~~ ## 選項 Option `Option`?是一個表示有可能包含值的容器。 Option基本的接口是這樣的: ~~~ trait Option[T] { def isDefined: Boolean def get: T def getOrElse(t: T): T } ~~~ Option本身是泛型的,并且有兩個子類:?`Some[T]`?或?`None` 我們看一個使用Option的例子: `Map.get`?使用?`Option`?作為其返回值,表示這個方法也許不會返回你請求的值。 ~~~ scala> val numbers = Map("one" -> 1, "two" -> 2) numbers: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2) scala> numbers.get("two") res0: Option[Int] = Some(2) scala> numbers.get("three") res1: Option[Int] = None ~~~ 現在我們的數據似乎陷在`Option`中了,我們怎樣獲取這個數據呢? 直覺上想到的可能是在`isDefined`方法上使用條件判斷來處理。 ~~~ // We want to multiply the number by two, otherwise return 0. val result = if (res1.isDefined) { res1.get * 2 } else { 0 } ~~~ 我們建議使用`getOrElse`或模式匹配處理這個結果。 `getOrElse`?讓你輕松地定義一個默認值。 `val result = res1.getOrElse(0) * 2` 模式匹配能自然地配合`Option`使用。 ~~~ val result = res1 match { case Some(n) => n * 2 case None => 0 } ~~~ **參考**?Effective Scala 對使用[Options](http://twitter.github.com/effectivescala/#Functional programming-Options)的意見。 # 函數組合子(Functional Combinators) `List(1, 2, 3) map squared`對列表中的每一個元素都應用了`squared`平方函數,并返回一個新的列表`List(1, 4, 9)`。我們稱這個操作`map`?*組合子*。 (如果想要更好的定義,你可能會喜歡Stackoverflow上對[組合子的說明](http://stackoverflow.com/questions/7533837/explanation-of-combinators-for-the-working-man)。)他們常被用在標準的數據結構上。 ## map `map`對列表中的每個元素應用一個函數,返回應用后的元素所組成的列表。 ~~~ scala> numbers.map((i: Int) => i * 2) res0: List[Int] = List(2, 4, 6, 8) ~~~ 或傳入一個部分應用函數 ~~~ scala> def timesTwo(i: Int): Int = i * 2 timesTwo: (i: Int)Int scala> numbers.map(timesTwo _) res0: List[Int] = List(2, 4, 6, 8) ~~~ ## foreach `foreach`很像map,但沒有返回值。foreach僅用于有副作用[side-effects]的函數。 ~~~ scala> numbers.foreach((i: Int) => i * 2) ~~~ 什么也沒有返回。 你可以嘗試存儲返回值,但它會是Unit類型(即void) ~~~ scala> val doubled = numbers.foreach((i: Int) => i * 2) doubled: Unit = () ~~~ ## filter `filter`移除任何對傳入函數計算結果為false的元素。返回一個布爾值的函數通常被稱為謂詞函數[或判定函數]。 ~~~ scala> numbers.filter((i: Int) => i % 2 == 0) res0: List[Int] = List(2, 4) ~~~ ~~~ scala> def isEven(i: Int): Boolean = i % 2 == 0 isEven: (i: Int)Boolean scala> numbers.filter(isEven _) res2: List[Int] = List(2, 4) ~~~ ## zip `zip`將兩個列表的內容聚合到一個對偶列表中。 ~~~ scala> List(1, 2, 3).zip(List("a", "b", "c")) res0: List[(Int, String)] = List((1,a), (2,b), (3,c)) ~~~ ## partition `partition`將使用給定的謂詞函數分割列表。 ~~~ scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> numbers.partition(_ % 2 == 0) res0: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9)) ~~~ ## find `find`返回集合中第一個匹配謂詞函數的元素。 ~~~ scala> numbers.find((i: Int) => i > 5) res0: Option[Int] = Some(6) ~~~ ## drop & dropWhile `drop`?將刪除前i個元素 ~~~ scala> numbers.drop(5) res0: List[Int] = List(6, 7, 8, 9, 10) ~~~ `dropWhile`?將刪除元素直到找到第一個匹配謂詞函數的元素。例如,如果我們在numbers列表上使用`dropWhile`奇數的函數,?`1`將被丟棄(但`3`不會被丟棄,因為他被`2`“保護”了)。 ~~~ scala> numbers.dropWhile(_ % 2 != 0) res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10) ~~~ ## foldLeft ~~~ scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n) res0: Int = 55 ~~~ 0為初始值(記住numbers是List[Int]類型),m作為一個累加器。 直接觀察運行過程: ~~~ scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n } m: 0 n: 1 m: 1 n: 2 m: 3 n: 3 m: 6 n: 4 m: 10 n: 5 m: 15 n: 6 m: 21 n: 7 m: 28 n: 8 m: 36 n: 9 m: 45 n: 10 res0: Int = 55 ~~~ ### foldRight 和foldLeft一樣,只是運行過程相反。 ~~~ scala> numbers.foldRight(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n } m: 10 n: 0 m: 9 n: 10 m: 8 n: 19 m: 7 n: 27 m: 6 n: 34 m: 5 n: 40 m: 4 n: 45 m: 3 n: 49 m: 2 n: 52 m: 1 n: 54 res0: Int = 55 ~~~ ## flatten `flatten`將嵌套結構扁平化為一個層次的集合。 ~~~ scala> List(List(1, 2), List(3, 4)).flatten res0: List[Int] = List(1, 2, 3, 4) ~~~ ## flatMap `flatMap`是一種常用的組合子,結合映射[mapping]和扁平化[flattening]。 flatMap需要一個處理嵌套列表的函數,然后將結果串連起來。 ~~~ scala> val nestedNumbers = List(List(1, 2), List(3, 4)) nestedNumbers: List[List[Int]] = List(List(1, 2), List(3, 4)) scala> nestedNumbers.flatMap(x => x.map(_ * 2)) res0: List[Int] = List(2, 4, 6, 8) ~~~ 可以把它看做是“先映射后扁平化”的快捷操作: ~~~ scala> nestedNumbers.map((x: List[Int]) => x.map(_ * 2)).flatten res1: List[Int] = List(2, 4, 6, 8) ~~~ 這個例子先調用map,然后可以馬上調用flatten,這就是“組合子”的特征,也是這些函數的本質。 **參考**?Effective Scala 對[flatMap](http://twitter.github.com/effectivescala/#Functional programming-`flatMap`)的意見。 ## 擴展函數組合子 現在我們已經學過集合上的一些函數。 我們將嘗試寫自己的函數組合子。 有趣的是,上面所展示的每一個函數組合子都可以用fold方法實現。讓我們看一些例子。 ~~~ def ourMap(numbers: List[Int], fn: Int => Int): List[Int] = { numbers.foldRight(List[Int]()) { (x: Int, xs: List[Int]) => fn(x) :: xs } } scala> ourMap(numbers, timesTwo(_)) res0: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) ~~~ 為什么是List[Int]()?Scala沒有聰明到理解你的目的是將結果積聚在一個空的Int類型的列表中。 ## Map? 所有展示的函數組合子都可以在Map上使用。Map可以被看作是一個二元組的列表,所以你寫的函數要處理一個鍵和值的二元組。 ~~~ scala> val extensions = Map("steve" -> 100, "bob" -> 101, "joe" -> 201) extensions: scala.collection.immutable.Map[String,Int] = Map((steve,100), (bob,101), (joe,201)) ~~~ 現在篩選出電話分機號碼低于200的條目。 ~~~ scala> extensions.filter((namePhone: (String, Int)) => namePhone._2 < 200) res0: scala.collection.immutable.Map[String,Int] = Map((steve,100), (bob,101)) ~~~ 因為參數是元組,所以你必須使用位置獲取器來讀取它們的鍵和值。呃! 幸運的是,我們其實可以使用模式匹配更優雅地提取鍵和值。 ~~~ scala> extensions.filter({case (name, extension) => extension < 200}) res0: scala.collection.immutable.Map[String,Int] = Map((steve,100), (bob,101)) ~~~ 為什么這個代碼可以工作?為什么你可以傳遞一個部分模式匹配? 敬請關注下周的內容! Built at?[@twitter](http://twitter.com/twitter)?by?[@stevej](http://twitter.com/stevej),?[@marius](http://twitter.com/marius), and?[@lahosken](http://twitter.com/lahosken)?with much help from?[@evanm](http://twitter.com/evanm),?[@sprsquish](http://twitter.com/sprsquish),?[@kevino](http://twitter.com/kevino),?[@zuercher](http://twitter.com/zuercher),?[@timtrueman](http://twitter.com/timtrueman),?[@wickman](http://twitter.com/wickman), and[@mccv](http://twitter.com/mccv); Russian translation by?[appigram](https://github.com/appigram); Chinese simple translation by?[jasonqu](https://github.com/jasonqu); Korean translation by?[enshahar](https://github.com/enshahar); Licensed under the?[Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0).
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看