A higher-order function treats functions as values: it accepts one or more functions as arguments, returns a function, or does both. This lets a program combine pure functions instead of repeating surrounding logic. section 2.0 section 2.3
Factor out the shared work
Instead of maintaining nearly identical formatAbs and formatFactorial functions, pass the changing operation into one function: def formatResult(name: String, n: Int, f: Int => Int) = val msg = "The %s of %d is %d." msg.format(name, n, f(n)) The type Int => Int says that f receives an Int and returns an Int. Both abs and factorial fit that contract: formatResult("absolute value", -42, abs) formatResult("factorial", 7, factorial) The shared formatting remains in one place while the calculation varies. The function parameter carries the behavior that would otherwise be duplicated. section 2.3.2
The absolute value of -42 is 42 The factorial of 7 is 5040
Use the sample output to connect the reusable formatter with its two different function arguments. section 2.3
A function literal supplies behavior inline when naming it would add ceremony: findFirst(Array(7, 9, 13), (x: Int) => x == 9). Scala can infer argument types from context, and shorthand such as _ > _ can express comparisons. A polymorphic higher-order function can generalize this pattern: isSorted[A](as: Array[A], gt: (A, A) => Boolean) delegates ordering to gt rather than assuming operations on A. section 2.4.2
Higher-order functions also support reusable function-building operations:
- partial1 fixes one argument of a two-argument function and returns a one-argument function: (b: B) => f(a, b). section 2.5
- curry and uncurry convert between two-argument functions and functions returning functions. section 2.5
- compose and andThen connect functions so one result becomes another function's input. section 2.5













