Scala高阶函数示例
2014-09-02 10:36 Rollen Holt 阅读(2303) 评论(0) 编辑 收藏 举报object Closure {
def function1(n: Int): Int = {
val multiplier = (i: Int, m: Int) => i * m
multiplier.apply(n, 2)
}
def function2(m: Int => Int) = m
def function3(f: (Int, Int) => Int) = f
val function4 = (x: Int) => x + 1
val function5 = (x:Int) => {
if(x > 1){
//...
}else{
//...
}
}
val function6 = (_ : Int) + ( _ :Int)
def function7(a:Int, b:Int, c:Int) = a+b+c
val function8 = function7 _
val function9 = function7(1, _:Int, 3)
def function10(x:Int) = (y:Int) => x+y
def function11(args: Int*) = for (arg <- args) println(arg)
def function12(x: Int): Int = {
if (x == 0) {
throw new Exception("bang!")
}
else{
function12(x -1)
}
}
def hello1(m: Int): Int = m
def hello2(m: Int, n: Int): Int = m * n
def main(args: Array[String]) {
println(function1(2))
println(function2(hello1)(2))
println(function3(hello2)(2, 3))
println(function4(4))
println(function4(5))
function6(1, 2)
function8(1, 2, 3)
function8.apply(1, 2, 3)
function9.apply(1)
function10(1)(2)
function11(1, 2, 3, 4)
function11(Array(1, 2, 3): _*)
}
}
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================