3.1 Higher Order Function - Gaoey/scala-diary GitHub Wiki
HOF is passing functions to functions
The first new idea is this:
functions are values.
And just like values of other types—such as integers, strings, and lists—functions can be assigned to variables, stored in data structures, and passed as arguments to functions.
When writing purely functional programs, we’ll often find it useful to write a function that accepts other functions as arguments. This is called a higher-order function (HOF)
from:
Functional Programming in Scala - By PAUL CHIUSANO, RÚNAR BJARNASON
higher order function คือ การที่เราสามารถโยน function เข้าไปในฟังก์ชันได้, function เป็น argument ได้
object Sort {
def isSorted[A](as: Seq[A], ordering: (A, A) => Boolean): Boolean = {
@annotation.tailrec
def go(n: Int): Boolean =
if (n >= as.length - 1)
true
else if (ordering(as(n), as(n + 1)))
false
else
go(n + 1)
go(0)
}
}
Sort.isSorted(Array(1, 3, 5, 7), (x: Int, y: Int) => x > y) should be(true)
Sort.isSorted(Array(7, 5, 1, 3), (x: Int, y: Int) => x < y) should be(false)