Scala的高阶函数


点击(此处)折叠或打开

  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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1850040/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值