天天看点

Scala高阶函数详解

概述

Scala高阶函数详解

函数参数,即传入另一个函数的参数是函数

//((Int)=>String)=>String

scala> def convertIntToString(f:(Int)=>String)=f(4)

convertIntToString: (f: Int => String)String

scala> convertIntToString((x:Int)=>x+" s")

res32: String = 4 s

(2)返回值是函数

//中的API: 
Scala高阶函数详解
Scala中的常用高阶函数
  1. map函数

的map⇒ B): Array[B]

的含义:the functionto apply to each element.

得到的是重复的n操作的一个特点

scala> Array("spark","hive","hadoop").map((x:String)=>x*2)

res3: Array[String] = Array(sparkspark, hivehive, hadoophadoop)

//单个参数,还可以省去括号

scala> Array("spark","hive","hadoop").map(x=>x*2)

res5: Array[String] = Array(sparkspark, hivehive, hadoophadoop)

//写法2

scala> list.map(_._1)

res21: List[String] = List(Spark, hive, hadoop)

scala> list.map(_._2)

res22: List[Int] = List(1, 2, 2)

Map类型:

//写法1

scala> List(List(1,2,3),List(2,3,4)).flatMap(x=>x)

res40: List[Int] = List(1, 2, 3, 2, 3, 4)

scala> Array(1,2,4,3,5).reduce((x:Int,y:Int)=>{println(x,y);x+y})

(1,2)

(3,4)

(7,3)

(10,5)

res60: Int = 15

scala> Array(1,2,4,3,5).reduceLeft((x:Int,y:Int)=>{println(x,y);x+y})

res61: Int = 15

scala> Array(1,2,4,3,5).reduceRight((x:Int,y:Int)=>{println(x,y);x+y})

(3,5)

(4,8)

(2,12)

(1,14)

res62: Int = 15

  1. fold函数

scala> Array(1,2,4,3,5).foldLeft(0)((x:Int,y:Int)=>{println(x,y);x+y})

(0,1)

res66: Int = 15

scala> Array(1,2,4,3,5).foldRight(0)((x:Int,y:Int)=>{println(x,y);x+y})

(5,0)

res67: Int = 15

scala> Array(1,2,4,3,5).foldLeft(0)(_+_)

res68: Int = 15

scala> Array(1,2,4,3,5).foldRight(10)(_+_)

res69: Int = 25

// /:  主要的区别是fold是从右开始算,然后往左遍历。而fold由于fold  第一个限制是初始值的类型必须是list计算,而初始值是Int  第二个限制是初始值必须是中立的(neutral),对于list函数

//在java进行代码开发):

var counter=0;

val button=new JButton("click")

button.addActionListener(new ActionListener{

overridedef actionPerformed(event:ActionEvent){

counter+=1

}

})

接口的匿名内部类,代码中

new ActionListener{

override def actionPerformed(event:ActionEvent){

方法,它被称为simple abstract method(SAM)方法传递一个参数

button.addActionListener((event:ActionEvent)=>counter+=1)

//编程的时候,可以省略非常多的样板代码,使代码更简洁。

函数柯里化

该函数的输入是Doulbe变量x这是高阶函数调用的另外一种形式

scala> multiplyBy(10)(50)

res77: Double = 500.0

函数定义成如下形式

scala> def multiplyBy(factor:Double)(x:Double)=x*factor

multiplyBy: (factor: Double)(x: Double)Double

柯里化的函数调用方式

res81: Double = 500.0

//错误提示函数multiplyBy在数组那一节中,我们讲到,Scala上面的代码等价于下面的代码

scala> def print(x:String)=println(x)

print: (x: String)Unit

scala> Array("Hadoop","Hive","Spark")foreach(print)

Hadoop

Hive

Spark

个参数,此时得到的函数便是部分应用函数,定义上述print的部分应用函数

scala> val p=print _

p: String => Unit = <function1>

scala> Array("Hadoop","Hive","Spark")foreach(p)

scala> Array("Hadoop","Hive","Spark")foreach(print _)

定义一个求和函数

scala> def sum(x:Int,y:Int,z:Int)=x+y+z

sum: (x: Int, y: Int, z: Int)Int

//指定一个参数的部分应用函数

scala> val s3=sum(1,_:Int,_:Int)

s3: (Int, Int) => Int = <function2>