函数作为参数传递
代码如下:
package function
/**
* 用于测试函数的传递与高阶函数的调用
*
* */
object Function {
def sum(f : Int => Int , a : Int ,b : Int): Int =
if (a > b) 0 else f(a) + sum(f,a+1,b)
def square(x : Int ) : Int = x*x
def powerOfTwo(x : Int) : Int = if( x == 0 ) 1 else 2 * powerOfTwo(x-1)
def main(a : Array[String]): Unit = {
/*将第一个函数参数设置为默认的求平方的函数,然后输入后面的a,b*/
val f1 = sum(square,_ : Int , _ : Int)
println(f1(2,5))
}
}
输出结果:
54
返回值为函数
代码如下:
package function
object FunctionReturn {
def returnFunc(a : Int , b : Int) : (Int , Int) => Int = {
def sum(a : Int,b : Int): Int = a+b
//返回sum这个函数
sum
}
def main(a : Array[String]) : Unit = {
val f = returnFunc(45,45)
println(f)
}
}
输出结果:
<function2>
函数和柯里化
代码
def sum(f: Int => Int)(a: Int, b: Int): Int =
if(a > b) 0 else f(a) + sum(f)(a + 1, b)
这样使使用函数更加方便,简洁
看下面的代码
package function
object Functioncurrying {
def sum(f : (Int,Int) => Int)(a : Int,b : Int) : Int ={
f(a,b)
}
def test(a : Int,b : Int) : Int = a+b
def main(a : Array[String]): Unit = {
//省略后面的参数
val f = sum(test)_
println(f(12,23))
}
}
输出结果为35