liveBook · Manning

Higher-order function

As explained in Elixir in Action, Third Edition

A higher-order function is a function that accepts one or more functions as arguments, returns one or more functions, or both.

A higher-order function accepts function values as arguments, returns function values, or does both. In Elixir, it hides recursive iteration behind reusable operations such as Enum.each/2, reducing repetitive loop and tail-recursion code. section 3.4.3

Common Enum operations apply function values to enumerable data:

  • Enum.each/2 invokes a lambda for every element without returning a transformed collection. section 3.4.3
  • Enum.map/2 performs one-to-one transformation, while capture syntax such as &(2 * &1) makes short functions denser. section 3.4.3
  • Enum.filter/2 retains elements selected by a predicate, including reporting missing fields with Map.has_key?/2. section 3.4.3
  • Enum.reduce/3 passes each element and accumulator to a function, supporting sums, validation guards, and custom accumulation. section 3.4.3
iex(4)> Enum.reduce(
          [1, 2, 3],
          0,                                      #1
          fn element, sum -> sum + element end    #2
        )
6

A runnable Enum.reduce/3 example shows a higher-order function receiving an enumerable, an initial accumulator, and a callback that computes the sum. section 3.4.3

How Elixir in Action, Third Edition covers it

How deep it goes
Defines the mechanism and works through Enum examples, but defers enumerable contracts and broader lazy iteration details.
Examples
Demonstrates printing, doubling, filtering odd numbers, reporting missing fields, summing values, and ignoring nonnumeric elements.
What it assumes
Assumes familiarity with functions, lambdas, and lists while briefly treating enumerables as structures satisfying the Enum contract.
What you can do after
Apply via Enum functions to iterate, transform, filter, and reduce enumerable data with less recursive boilerplate.
How it connects
Connects higher-order functions with lambdas, recursion, tail recursion, enumerables, Enum, Stream, and comprehensions.

Also explained in

Compare how 14 books explain higher-order function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.