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

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))

Design rule

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.