ELIXIR / CHAPTER 07

Enum pipelines and reductions

Advanced

Transform a collection through explicit ordered stages.

By the end of this chapter

  • Use the pipeline’s first-argument rule
  • Distinguish filtering from mapping
  • Choose a reduction’s accumulator value

The idea

Enter with functions and lists understood. The pipeline operator sends the value on its left into the first argument position of the call on its right. It makes a sequence of transformations readable in data-flow order. Enum.filter retains selected elements, Enum.map transforms each retained element, and Enum.reduce combines them into one result using an explicit starting accumulator.

Enum operations generally process enumerables eagerly, so an intermediate list may be built at each stage. This is different from assuming every functional-looking pipeline is lazy. For small finite collections, clarity is often the primary concern; a streaming design can be chosen separately when needed. In reductions, remember that the anonymous function receives the current element before the accumulator. Choose the initial accumulator from the operation’s meaning.

Elixir example
result = [1, 4, 7, 8]
  |> Enum.filter(fn n -> rem(n, 2) == 0 end)
  |> Enum.map(fn n -> n * 3 end)
  |> Enum.sum()
IO.inspect(result)
Result
36

The filter keeps four and eight. Tripling produces twelve and twenty-four, whose sum is thirty-six.

Try it yourself

Use Enum.reduce to count values above a threshold without changing the source list.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does values |> Enum.map(fun) mean?