ITPub博客

首页 > 应用开发 > Java > Scala的高阶函数

Scala的高阶函数

原创 Java 作者:541732025 时间:2015-11-30 21:24:40 0 删除 编辑

点击(此处)折叠或打开

  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博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1850040/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Scala中的闭包
下一篇: Scala的ACM转换
请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    515720