Reference ยท Functional Programming in Scala
Higher-order functions
The compact reference for Lesson 02.
Standalone
All examples are original and use only small values. No VPS, account, private repository, production data, network service, or CLI is required.
Optional Scala source for syntax comparison.
Definition
A higher-order function takes a function as an argument, returns a function, or both.
Read the arrows
Int => Intโ one integer in, one integer out.(A, A) => Booleanโ two values of the same type, then a decision.A => B => Cโ anAproduces a function that acceptsBand producesC.
Reusable traversal
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
@annotation.tailrec
def go(n: Int): Boolean =
if (n >= as.length - 1) true
else if (!ordered(as(n), as(n + 1))) false
else go(n + 1)
go(0)
}
The loop is stable; the ordering policy is supplied by the caller.
Follow the types
def partial1[A, B, C](a: A, f: (A, B) => C): B => C =
b => f(a, b)
def compose[A, B, C](f: B => C, g: A => B): A => C =
a => f(g(a))
partial1captures the value already known and waits for the missing value.composerunsgfirst, because its output has the type required byf.
Design rule
- Keep the traversal or pipeline in one pure function.
- Pass policy, comparison, formatting, or transformation as a function.
- Use type parameters when the algorithm does not care about the concrete element type.
- Test the pure core with multiple policies before adding I/O.
Rust translation
Think of this as passing a closure into a generic Rust function. The important move is the same: the algorithm owns the structure, while the caller supplies behavior.