Scala 集合 - Reduce 方法



reduce() 方法是 TraversableOnce 特性 的成員,用於摺疊集合中的元素。它類似於 fold 方法,但它不接受初始值。

語法

以下是 reduce 方法的語法。

def reduce[A1 >: A](op: (A1, A1) ? A1): A1

這裡,reduce 方法將關聯二元運算子函式作為引數。此方法返回結果值。

用法

下面是一個示例程式,展示瞭如何使用 fold 方法 -

示例

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.reduce(_ + _)
      //print result
      println(result)      
   }
}

將上述程式儲存到 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

10
廣告

© . All rights reserved.