liveBook · Manning

Enum.reduce/3

As explained in Elixir in Action, Third Edition

Enum.reduce/3 traverses an enumerable while repeatedly applying a function to each element and an accumulator, returning the final accumulator.

Enum.reduce/3 transforms an enumerable into any accumulated result. It receives the enumerable, an initial accumulator, and a function called for each element; that function returns the next accumulator, and the final accumulator becomes the result. section 3.4.3

Summing a list

Enum.reduce([1, 2, 3], 0, fn element, sum -> sum + element end) returns 6. The initial value is 0, and each invocation computes the next sum without mutating the previous accumulator. The shorter Enum.reduce([1, 2, 3], 0, &+/2) form expresses the same operation. section 3.4.3

Building a structure iteratively

A constructor can reduce raw entries into a TodoList struct by starting with %TodoList{} and calling add_entry/2 for each entry. Because reduce passes the element before the accumulator, the capture form reverses them with &add_entry(&2, &1). section 4.2.4

How Elixir in Action, Third Edition covers it

How deep it goes
Explains the three arguments, per-element accumulator updates, immutable progression, shorthand, guards, and iterative construction.
Examples
Uses list summation, guarded numeric filtering during accumulation, and iterative TodoList construction.
What it assumes
Assumes familiarity with functions and lambdas while demonstrating functional accumulator updates from an imperative loop comparison.
What you can do after
Apply it via Enum.reduce/3 to calculate results or construct structures from enumerable data.
How it connects
Connects reduction with higher-order functions, accumulators, capture operators, pattern matching, and enumerable transformations.

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.