首页 > 代码库 > scala高阶函数总结

scala高阶函数总结

1、值函数

    将一个函数赋值给某个变量,此变量就是一个值函数

    scala> import scala.math._

    import scala.math._



    scala> val fun = sqrt _

    fun: Double => Double = <function1>


    scala> fun(25)

    res19: Double = 5.0

2、匿名函数

    无名称的函数,即为匿名函数,通常使用在函数的参数中

    scala> (1 to 9).reduceLeft(_ + _)

    res20: Int = 45


    scala> (1 to 9).reduceLeft( (x:Int,y:Int) => x+y)

    res21: Int = 45

3、高阶函数

    以函数做为参数的函数就是高阶函数

    scala> def valueAtQuarter(fun: (Double) => Double) = fun(4)

    valueAtQuarter: (fun: Double => Double)Double


    scala> valueAtQuarter(scala.math.sqrt _)

    res22: Double = 2.0

4、柯里化

    将多个参数的函数分离,使其通过两次调用,有点说不清楚,直接上代码。。。

    scala> def mul (x: Int,y: Int) = x * y

    mul: (x: Int, y: Int)Int


    scala> def mul(x : Int) = (y: Int) => x * y

    mul: (x: Int)Int => Int


    scala> val x=mul(6)

    x: Int => Int = <function1>


    scala> x(5)

    res23: Int = 30


    scala> mul(6)(5)

    res24: Int = 30

    说明:mul(6)(5)先执行mul(6)返回一个函数再调用(5)


    scala> def mul(x: Int)(y: Int)= x *y

    mul: (x: Int)(y: Int)Int

    这种写法比较容易理解,和def mul(x : Int) = (y: Int) => x * y等效

5、控制抽象

    执行一个代码块的内容,可以定义一个无参无返回的函数


def runThread(block: () => Unit){

  new Thread{

     override def run() {block() }

  }.start()

}

runThread( () => println("start");Thread.sleep(1000);println("end") )

飘红部分可以省略,增加代码可读性

6、控制抽象与柯里化的结合实例

    

def until(condition: => Boolean)(block: =>Unit){

  if(!condition){

     block

     until(condition)(block)

  }

}

说明:condition: => Boolean等价condition: () => Boolean

        block: =>Unit等价 block: () =>Unit

本文出自 “滴水石穿” 博客,请务必保留此出处http://chengyanbin.blog.51cto.com/3900113/1606067

scala高阶函数总结