scala高阶函数
1.作为值的函数
import scala.math._ object Test extends App { //scala中函数是头等公民,可以像其他类型一样被传递 val num = 3.14 val fun: Double => Double = ceil _ //将ceil方法转成函数 //调用函数 println(fun(4)) //传递给其他函数 val a = Array(3.14,1.42,2.5).map(fun) }
2.匿名函数
object Test extends App { //匿名函数 val fun1 = (x: Double) => x * 3 def fun2(x: Double) = { x * 3 } }
3.带函数参数的函数
import scala.math._ object Test extends App { def valueAtOneQuarter(num: Double, f: Double => Double) = { f(num) } val result = valueAtOneQuarter(25, ceil _) println(result) val a: (Double, Double => Double) => Double = valueAtOneQuarter _ //函数类型 (Double, Double => Double) => Double //函数产出函数 def mulBy(factor:Double) = { (x:Double)=>x*3 } val b: Double => Double => Double = mulBy _ }
4.参数类型推断
object Test extends App { def valueAtOneQuarter(f: Double => Double) = { f(0.25) } valueAtOneQuarter((x: Double) => 3 * x) //scala会自动推断类型 valueAtOneQuarter((x) => 3 * x) //只有一个参数 括号可省略 valueAtOneQuarter(x => 3 * x) //参数在=>右侧值出现一次 可用下划线替换 valueAtOneQuarter(3 * _) }
5.闭包
object Test extends App { def mulBy(factor: Double) = (x: Double) => factor * x val triple = mulBy(3) val result1 = triple(2) println(result1) }
6.柯里化
object Test extends App { // 柯里化:将原来接收两个参数的函数变成接收一个参数的函数的过程 //新的函数返回一个以原有第二个参数作为参数的函数 def mul(x: Int, y: Int) = x + y def mulOneAtATime(x: Int) = (y: Int) => x + y println(mul(1, 2)) println(mulOneAtATime(1)(2)) def mulOneAtATimeNew(x: Int)(y: Int) = x + y }