Scala的高階函式

541732025發表於2015-11-30

點選(此處)摺疊或開啟

  1. def main(args: Array[String]){
  2.     
  3.     (1 to 9).map("*" * _).foreach(println _)
  4.     (1 to 9).filter(_ % 2 == 0) .foreach(println)
  5.     println((1 to 9).reduceLeft(_ * _))
  6.     "Spark is the most exciting thing happening in big data today".split(" ").
  7.         sortWith(_.length < _.length).foreach(println)
  8.     
  9.     val fun = ceil _
  10.     val num = 3.14
  11.     println(fun(num) )
  12.    Array(3.14, 1.42, 2.0).map(fun).foreach(println)
  13.     
  14.     val triple = (x: Double) => 3 * x
  15.     Array(3.14, 1.42, 2.0).map((x: Double) => 3 * x)
  16.     Array(3.14, 1.42, 2.0).map{ (x: Double) => 3 * x }
  17.     
  18.     def high_order_functions(f: (Double) => Double) = f(0.25) //定義函式high_order_functions,引數是另一個函式f,f的引數是Double,返回值也是Double,具體表現形式是f(0.25)
  19.     println(high_order_functions(ceil _)) //具體為ceil(0.25)
  20.     println(high_order_functions(sqrt _)) //具體為sqrt(0.25)
  21.     
  22.     def mulBy(factor: Double) = (x: Double) => factor * x //定義函式mulBy,引數是x
  23.     val quintuple = mulBy(5)
  24.     println(quintuple(20))
  25.     
  26.     println(high_order_functions((x: Double) => 3 * x))
  27.     high_order_functions((x) => 3 * x)
  28.     high_order_functions(x => 3 * x)
  29.     
  30.     println(high_order_functions(3 * _))
  31.     
  32.     val fun2 = 3 * (_: Double)
  33.     val fun3: (Double) => Double = 3 * _
  34.     
  35.   }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-1850040/,如需轉載,請註明出處,否則將追究法律責任。

相關文章