菜鳥理解的Scala高階函數

Scala中的高階函數,主要包含三種:

  1. 函數的參數是函數。
  2. 函數的返回值是函數。
  3. 函數的參數和返回值都是函數。

下面通過三種不同的函數形式,來實現階乘。

1、函數的參數是函數    已知函數1實現階乘計算,在函數2中使用函數1

    def fun1(i: Int): Int = {
      if (i == 1)
        i
      else
        i * fun1(i - 1)
    }

    def fun2(f: (Int) => Int, i: Int) = {
      val result = f(i)
      println(result)
    }

    fun2(fun1, 5);

2、函數的返回值是函數      已知函數1實現階乘計算,在函數2中使用函數1,並作爲結果返回

    def fun1(i: Int): Int = {
      if (i == 1)
        i
      else
        i * fun1(i - 1)
    }

    def fun2(): (Int) => Int = {
      //參數在調用fun2時傳遞給fun1
      fun1
    }
    println(fun2()(5))

3、函數的參數和返回值都是函數        已知函數1打印測試信息,函數2實現計算,函數3調用函數1,2

    def fun1(): Unit = {
      println("this is high function od the scala")
    }

    def fun2(i: Int): Int = {
      if (i == 1)
        i
      else
        i * fun2(i - 1)
    }

    def fun3(f: () => Unit): (Int) => Int = {
      //調用函數f需要寫上(),執行fun1()
      f()
      fun2
    }

    println(fun3(fun1)(5))

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章