# 一級函式（First-class function）

``def max(m: Int, n: Int) = if(m > n) m else n``

``val max = (m: Int, n: Int) => if(m > n) m else n``

val max: (Int, Int) => Int = (m: Int, n: Int) => if(m > n) m else n

``def selection(number: Array[Int], order: (Int, Int) => Boolean) {    def mm(m: Int, j: Int): Int = {        if(j == number.length) m        else if(order(number(j), number(m))) mm(j, j + 1)         else mm(m, j + 1)    }    for(i <- 0 until number.length -1; m = mm(i, i + 1)        if i != m    ) swap(number, i, m)}def swap(number: Array[Int], i: Int, j: Int) {    val t = number(i)    number(i) = number(j)    number(j) = t}``

``val arr1 = Array(2, 5, 1, 7, 8)selection(arr1, (a: Int, b: Int) => a < b)println(arr1.mkString(","))                  // 顯示 1,2,5,7,8``

``val arr2 = Array(2, 5, 1, 7, 8)selection(arr2, (a: Int, b: Int) => a > b)println(arr2.mkString(","))                  // 顯示 8,7,5,2,1``

``val arr2 = Array(2, 5, 1, 7, 8)selection(arr2, (a, b) => a > b)println(arr2.mkString(","))                  // 顯示 8,7,5,2,1``

``val arr2 = Array(2, 5, 1, 7, 8)selection(arr2, (_: Int) > (_: Int))println(arr2.mkString(","))                 // 顯示 8,7,5,2,1``

``val arr2 = Array(2, 5, 1, 7, 8)selection(arr2, _ > _)println(arr2.mkString(","))                 // 顯示 8,7,5,2,1``

``val f = (_: Int) + (_: Int)    // 這樣 OKprintln(f(1, 2))               // 顯示 3``

val f = _ + _            // 錯誤 missing parameter type for expanded function

``Array("a", "b", "c").foreach(x => print(x.toUpperCase)) // 顯示 ABC``

``Array(4, 8, 1, 6, 3, 7, 9).filter(_ > 5).foreach(print(_))  // 顯示 8、6、7、9``

``val max = (m: Int, n: Int) => {              if(m > n)                  m               else n          }``

``val max = (m: Int, n: Int) => if(m > n) m else nprintln(max(10, 20))          // 顯示 20println(max.apply(10, 20))    // 顯示 20``

``def toOneByRow(array: Array[Array[Int]]) = {    val arr = new Array[Int](array.length * array(0).length)    for(row <- 0 until array.length; column <- 0 until array(0).length) {        arr(row * array(0).length + column) = array(row)(column)     }    arr}    def toOneByColumn(array: Array[Array[Int]]) = {    val arr = new Array[Int](array.length * array(0).length)    for(row <- 0 until array.length; column <- 0 until array(0).length) {        arr(row + column * array.length) = array(row)(column)     }    arr}``

``def toOneByRow(array: Array[Array[Int]]) = {    toOne(array, _ * array(0).length + _)}    def toOneByColumn(array: Array[Array[Int]]) = {    toOne(array, _ + _ * array.length)}    def toOne(array: Array[Array[Int]], index: (Int, Int) => Int) = {    val arr = new Array[Int](array.length * array(0).length)    for(row <- 0 until array.length; column <- 0 until array(0).length) {        arr(index(row, column)) = array(row)(column)    }    arr    }``