23.Scala高阶函数实战详解
来源:互联网 发布:plsql数据库建表 编辑:程序博客网 时间:2024/06/06 07:57
高阶函数:把函数作为参数来传递。
即函数和值(整数或者字符串之类的)是一样的,函数是Scala的一等公民,函数可以保存在其他变量里。
Spark中主要用高阶函数。
object High_Order_Functions_23 { def main(args: Array[String]): Unit = { //7 (1 to 9).map("*" * _).foreach { println _ } //1是对象 to是方法 1 to 9是一个集合 1,2,3,4...9 map方法迭代集合中的每一个元素 foreach也是个函数 println (1 to 9).filter(_ % 2 == 0).foreach(println) //过滤出集合中的偶数 println println((1 to 9).reduceLeft(_ * _)) // 1*2*3*...*9 println "Spark is the most exciting thing happening in big data today".split(" ").sortWith(_.length < _.length).foreach(println) //按单词的长度升序排列 }}
输出:
*
**
***
****
*****
******
*******
********
*********
2
4
6
8
362880
is
in
the
big
most
data
Spark
thing
today
exciting
happening
val fun = ceil _ val num = 3.14 println(fun(num)) Array(3.14, 1.42, 2.0).map(fun).foreach(println)
输出:
4.0
4.0
2.0
2.0
val triple = (x : Double) => 3 * x //匿名函数 Array(3.14, 1.42, 2.0).map((x : Double) => 3 * x).foreach(println) Array(3.14, 1.42, 2.0).map((x : Double) => 3 * x).foreach{println
输出:
9.42
4.26
6.0
9.42
4.26
6.0
def high_order_functions(f: (Double) => Double) = f(0.25) //f是函数,(Double)是函数f的参数 println(high_order_functions(ceil _)) //把0.25交给ceil去处理 println(high_order_functions(sqrt _)) //把0.25交给sqrt去处理输出:
1.0
0.5
def mulBy(factor : Double) = (x : Double) => factor * x //x是运行时传入的参数 val quintuple = mulBy(5) println(quintuple(20))输出:100.0
println(high_order_functions( (x : Double) => 3 * x) ) //把(x : Double) => 3 * x)这个函数作用于high_order_functions println(high_order_functions((x) => 3 * x)) //可去掉:Double,因为high_order_functions函数输入是0.25,所以可推导出是输入类型是Double println(high_order_functions( x => 3 * x)) //只有一个输入参数,可去掉括号 println(high_order_functions( _ * 3)) //只有一个输入参数,可用占位符_代替输出:
0.75
0.75
0.75
0.75
val fun2 = 3 * (_ : Double) //: Double 不可以去掉,因为scala无法推导出类型 println(fun2(3)) val fun3 : (Double) => Double = 3 * _ println(fun3(8))
输出:
9.0
24.0
参考资料来源于 DT大数据梦工厂Scala零基础实战经典第23课 由王家林老师讲解
阅读全文
0 0
- 23.Scala高阶函数实战详解
- Scala深入浅出实战经典:23,Scala高阶函数实战详解
- Scala高阶函数操作示例详解
- Scala高阶函数
- Scala 高阶函数
- scala------高阶函数
- Scala高阶函数
- scala高阶函数
- scala高阶函数
- scala-高阶函数
- Scala高阶函数
- Scala 高阶函数
- scala高阶函数
- Scala高阶函数
- Scala高阶函数
- Scala-高阶函数
- 详解Scala的集合与高阶函数搭配
- 21.Scala中的偏函数实战详解
- 父母终于可以放心啦 安全上学 智慧校园电子班牌系统方案
- GCD and LCM HDU
- js 模拟百度音乐-全选操作
- C#索引器(Indexer)
- CSS+JS
- 23.Scala高阶函数实战详解
- git rebase简介
- 23种设计模式汇总整理
- MOB第三方使用
- iOS静态库(配置二)
- OpenCV学习笔记
- 编程学习公众号
- 转载文章1
- JAVA多线程同步详解