Chapter 4 — Pipes, Enum & Stream
Elixir’s daily-driver data flow. Concepts map directly onto the lists:
module — the syntax just got better, and laziness became first-class.
The chapter in one sentence: pipes shape how data flows, Enum executes
eagerly like lists:, and Stream defers execution so composition stays
cheap until a consumer pulls.
From Erlang you know:
Enumislists:with the arguments inverted, and nothing else.Streamhas nolists:equivalent — the closest thing in your current toolkit is a hand-rolled generator orqueue-based pipeline, which is why laziness is the genuinely new material here. The decision of when to be lazy is also new: in Erlang you rarely had the option.
4.1 Enum ↔ lists Module
Erlang (lists) | Elixir (Enum) |
|---|---|
lists:map(Fun, L) | Enum.map(list, fun) |
lists:filter(Pred, L) | Enum.filter(list, pred) |
lists:foldl(Fun, Acc, L) | Enum.reduce(list, acc, fun) |
lists:foreach(Fun, L) | Enum.each(list, fun) |
lists:all(Pred, L) | Enum.all?(list, pred) |
lists:any(Pred, L) | Enum.any?(list, pred) |
lists:member(E, L) | Enum.member?(list, elem) |
lists:reverse(L) | Enum.reverse(list) |
lists:sort(L) | Enum.sort(list) |
lists:usort(L) | Enum.sort(Enum.uniq(list)) — no single equivalent |
lists:uniq(L) | Enum.uniq(list) (both preserve first-seen order) |
lists:keystore(K, N, L, V) | Keyword.replace(opts, key, value) |
lists:keyfind(K, N, L) | Keyword.get(opts, key) / Map.fetch(map, key) |
lists:zip(A, B) | Enum.zip(a, b) |
lists:flatmap(Fun, L) | Enum.flat_map(list, fun) |
lists:partition(Pred, L) | Enum.split_with(list, pred) |
lists:split(N, L) | Enum.split(list, n) |
lists:takewhile(Pred, L) | Enum.take_while(list, pred) |
lists:dropwhile(Pred, L) | Enum.drop_while(list, pred) |
Two conventions to absorb with the table:
- Predicates end in
?(Enum.all?,Enum.member?) — boolean-ish functions read like questions. You’ll start writing your own predicates this way within days. - Data goes first. The collection is always the first argument and
the function/callback comes last. That inversion vs
lists:is exactly what makes pipes work (§4.2) — the piped value lands in the first argument slot.
Enum Works on More Than Lists
Erlang muscle memory says maps:to_list/1 before any iteration; in Elixir,
every Enum function accepts anything implementing the Enumerable
protocol (§5.2) — maps iterate as {key, value} pairs, ranges stream
without materializing:
iex> Enum.map(%{a: 1, b: 2}, fn {k, v} -> {k, v * 10} end)
[a: 10, b: 20]
iex> for {k, v} <- %{a: 1, b: 2}, v > 1, do: k # comprehensions too
[:b]
iex> Map.new([a: 1, b: 2], fn {k, v} -> {v, k} end) # build maps without
%{1 => :a, 2 => :b} # lists:foldl dances
The map-specific module still matters — Map.get/3, Map.update/4, and
friends are O(log n) keyed operations rather than full iterations — but the
“convert, iterate, rebuild” ritual is gone.
4.2 Pipes in Practice
The pipe passes the previous result as the first argument:
flowchart LR
S["1..10"] -->|"filter(is_even)"| A["[2, 4, 6, 8, 10]"]
A -->|"map(square)"| B["[4, 16, 36, 64, 100]"]
B -->|"sum()"| C["220"]
sum =
1..10
|> Enum.filter(&(rem(&1, 2) == 0))
|> Enum.map(&(&1 * &1))
|> Enum.sum()
#=> 220
Same program, eager Erlang style — note the bookkeeping of intermediate variables you no longer need:
List = lists:seq(1, 10),
Evens = lists:filter(fun(X) -> X rem 2 == 0 end, List),
Squared = lists:map(fun(X) -> X*X end, Evens),
Sum = lists:foldl(fun(X, Acc) -> X + Acc end, 0, Squared).
%% Sum = 220
Style rules you’ll absorb quickly:
- Pipe chains start from a raw value on its own line.
- Don’t pipe into
Enummore than ~5 steps without extracting a function. - Never pipe into a macro that doesn’t expect the value first.
Two Kernel helpers slot perfectly into chains — then/2 (transform) and
tap/2 (side effect, value passes through unchanged):
iex> 5 |> then(&(&1 * &1)) |> tap(&IO.puts("got #{&1}")) |> Kernel.+(1)
got 25
26
iex> user = %{name: "Ada"} |> put_in([Access.key!(:name)], "Grace")
Mental model: then replaces the value mid-chain; tap observes without
disturbing it — perfect for logging or dbg at any chain position.
Ranges Are First-Class
first..last creates inclusive ranges; append //step to step them; bare
.. is the full-slice range used in Access and binary_slice/2:
iex> Enum.to_list(1..5)
[1, 2, 3, 4, 5]
iex> Enum.to_list(1..10//2)
[1, 3, 5, 7, 9]
iex> Enum.to_list(10..1//-1) # descending needs an explicit negative step
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Ranges implement the Enumerable protocol (Ch 05), so every Enum/Stream
function works on them — including 1..10 |> Enum.sum() — without ever
building the list in between.
Deep Updates: put_in, update_in, get_in, pop_in
Nested structures update via path-based macros — the functional equivalent of walking pointers, rebuilt immutably at each level:
iex> user = %{name: "Ada", prefs: %{theme: "light", lang: "en"}}
iex> put_in(user.prefs.theme, "dark")
%{name: "Ada", prefs: %{theme: "dark", lang: "en"}}
iex> update_in(user.prefs.lang, &String.upcase/1)
%{name: "Ada", prefs: %{theme: "light", lang: "EN"}}
The dotted syntax works when keys are static; for runtime-computed paths,
pass explicit Access paths:
iex> key = :theme
iex> update_in(user, [Access.key!(:prefs), Access.key!(key)], fn
...> "light" -> "dark"
...> other -> other
...> end)
%{name: "Ada", prefs: %{lang: "en", theme: "dark"}}
Erlang needs hand-rolled nested updates for this; it is one of those conveniences that quietly changes how much nesting you will tolerate.
Comprehension Options: reduce: and uniq:
Two options cover the cases where bare for almost fits:
iex> for n <- 1..10, reduce: 0 do # threaded accumulator — a fold whose
...> acc when n > 5 -> acc + n # body is multi-clause
...> acc -> acc
...> end
40
iex> for w <- ~w(go stop go wait go), uniq: true, do: w
["go", "stop", "wait"]
iex> for <<c <- "abc">>, into: "", do: String.upcase(<<c>>)
"ABC"
With reduce: there is no implicit result list — the accumulator IS the
return value. Handy when accumulation logic branches per element and a
single reduce closure would need a case inside.
reduce_while: Fold With an Escape Hatch
Where Erlang’s foldl runs to completion unless you throw,
Enum.reduce_while/3 lets the fun decide per element:
iex> Enum.reduce_while(1..100, 0, fn i, acc ->
...> if acc + i >= 15, do: {:halt, acc + i}, else: {:cont, acc + i}
...> end)
15
iex> 1..100 |> Enum.take_while(&(&1 < 10)) |> Enum.sum()
45
{:halt, acc} stops and returns; {:cont, acc} continues. Pair with
take_while/drop_while when there is no accumulator to thread at all.
Comprehensions (for) — Special Form
for is a Kernel special form combining map/filter/reduce ergonomics
(generators <-, filters, into: for other collections):
iex> for n <- 1..10, rem(n, 2) == 0, do: n * n # generator + filter
[4, 16, 36, 64, 100]
iex> for {k, v} <- [a: 1, b: 2], into: %{}, do: {v, k} # collect into a map
%{1 => :a, 2 => :b}
# Multiple generators = cartesian product (nested loops, functionally):
iex> for x <- [1, 2], y <- [:a, :b], do: {x, y}
[{1, :a}, {1, :b}, {2, :a}, {2, :b}]
Reach for for when the operation reads naturally as “collect matching
transformations of these elements”; reach for reduce when state threads
through the iteration. They’re tools with overlapping territory — pick the
one that reads best.
4.3 Stream: Lazy, Composable Sequences
Stream mirrors Enum but builds a lazy computation. Nothing runs until a
final Enum operation pulls values through.
| Concept | Erlang (lists, eager) | Elixir (Stream, lazy) |
|---|---|---|
| Evaluation | Immediate per step | On demand |
| Memory | Intermediate lists each step | Constant (single pass) |
| Infinite sequences | Not practical | Stream.cycle/1, Stream.iterate/2 |
| Execution | At call time | At Enum.to_list/1, Enum.take/2, … |
Side by side on the same problem — sum the first five results of map→filter over 100k numbers:
flowchart TB
subgraph EAGER["Enum — eager: each step materializes"]
direction LR
E1["1..100_000"] --> E2["map ×100<br/>(100_000-elem list)"]
E2 --> E3["filter > 500<br/>(~100_000-elem list)"]
E3 --> E4["take 5<br/>FINALLY stops"]
end
subgraph LAZY["Stream — lazy: one element flows at a time"]
direction LR
L1["1..100_000"] -.->|"pull"| L2["map ×100"]
L2 -.-> L3["filter > 500"]
L3 -.->|"enough! stop pulling"| L4["take 5"]
end
style EAGER fill:#ffebee
style LAZY fill:#e8f5e9
# eager: maps/filters ALL 100_000 before taking 5
1..100_000 |> Enum.map(&(&1 * 100)) |> Enum.filter(&(&1 > 500)) |> Enum.take(5)
# lazy: stops after enough elements pass — never touches most of the range
1..100_000 |> Stream.map(&(&1 * 100)) |> Stream.filter(&(&1 > 500)) |> Enum.take(5)
#=> [600, 700, 800, 900, 1000]
Both return [600, 700, 800, 900, 1000]; the lazy version allocates no
intermediate lists and short-circuits after the fifth match.
Prove the short-circuit with a side effect rather than taking the word for
it. Each IO.puts fires only when its element is actually pulled:
iex> 1..5 |> Enum.map(fn x -> IO.puts("eager map #{x}"); x end) |> Enum.take(2)
eager map 1
eager map 2
eager map 3 # ← already ran, and its result was discarded
eager map 4 # ← ditto
eager map 5 # ← ditto
[1, 2]
iex> 1..5 |> Stream.map(fn x -> IO.puts("lazy map #{x}"); x end) |> Enum.take(2)
lazy map 1
lazy map 2
[1, 2] # three, four, five were never touched
That output is the whole argument for Stream, and it is worth internalizing
as a reflex: if a pipeline has a terminating consumer like take/2 early in
the chain, the eager version did work whose result you threw away.
A corollary that catches people: Enum.map over a huge collection is not
just slower than Stream.map — it holds the result in memory. Measured:
:erts_debug.size/1 reports 2,000,000 words for
Enum.to_list(1..1_000_000) — about 16 MB on a 64-bit VM, two words per cons
cell (the small integers are immediates, so they are not boxed). Streams
allocate none of that until a consumer forces materialization.
Infinite sequences are where streams stop being an optimization and become a different capability entirely:
iex> stream =
...> Stream.iterate(1, &(&1 + 1)) # infinite: 1, 2, 3, ...
...> |> Stream.map(&(&1 * 2)) # 2, 4, 6, ...
...> |> Stream.filter(&(&1 > 1000)) # 1002, 1004, ...
iex> Enum.take(stream, 10)
[1002, 1004, 1006, 1008, 1010, 1012, 1014, 1016, 1018, 1020]
iex> stream |> Enum.take(10) |> Enum.sum()
10110
Note the composition itself is instant (Stream.iterate on an infinite
sequence returns immediately) — nothing executes until an Enum function
pulls. Stream.run/1 drains a stream purely for side effects:
iex> ~w(a b c) |> Stream.each(&IO.puts(&1)) |> Stream.run()
a
b
c
:ok
Stream.resource/3: Wrapping External Handles
Streams shine when the data source needs lifecycle management — files,
sockets, cursors. Stream.resource/3 gives you three hooks: open (lazily),
next, close.
lines = fn path ->
Stream.resource(
fn -> File.open!(path) end, # start hook: runs at FIRST pull
fn device ->
case IO.read(device, :line) do
data when is_binary(data) -> {[data], device} # emit + continue
:eof -> {:halt, device} # stop pulling
end
end,
fn device -> File.close(device) end # after hook: guaranteed close
)
end
iex> "README.md" |> lines.() |> Enum.take(2) |> length()
2
iex> "README.md" |> lines.() |> Stream.map(&String.upcase/1) |> Stream.run()
:ok
Three properties worth memorizing:
- Lazy open — the file opens only when the first
Enumconsumer pulls; building and passing the stream costs nothing. - Close on completion or early halt — after successful initialization,
the after-fun runs both on natural exhaustion and when a consumer such
as
Enum.take/2stops early. Taking two lines closes the file; draining the remaining lines withStream.run/1is unnecessary. - Cleanup has limits — constructing a stream without consuming it opens nothing. Normal enumeration also runs cleanup if processing raises, but forcibly killing the consuming process can bypass cleanup. Do not rely on garbage collection to manage external resources.
Building Sequences: unfold and chunking
Stream.unfold/2 is the general stateful generator — each call returns
{value, next_state} or nil:
iex> fib = Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
iex> Enum.take(fib, 8)
[0, 1, 1, 2, 3, 5, 8, 13]
Chunking splits lazily too — windows with overlap, incomplete-part policy — without materializing the input:
iex> Enum.chunk_every(1..6, 4, 2, :discard) # window of 4, step 2
[[1, 2, 3, 4], [3, 4, 5, 6]]
Between unfold and chunk_while, most hand-rolled generators disappear.
In practice you rarely hand-roll the file wrapper at all — File.stream!/1
is exactly that Stream.resource machine, built in:
iex> File.stream!("README.md") |> Enum.take(2) |> length()
2
Two Limits of Laziness
Two behaviors surprise people who meet Stream after Enum:
- Laziness is not concurrency. A stream is a single-process,
single-pass pull machine — elements flow one at a time, in order, in
the consuming process. Parallelizing work per element is a different
tool:
Task.async_stream/3(Ch 05) or GenStage/Broadway (Ch 13). - Re-enumeration re-runs the work. A composed stream is a recipe,
not a cache. This one bites hardest because
Streamlooks like a collection, so you expectEnum.to_list(s)twice to mean the same values — it does, but at twice the side effects:
iex> tracked = Stream.map(1..3, fn i -> send(self(), {:ran, i}); i end)
iex> Enum.to_list(tracked)
[1, 2, 3]
iex> flush()
[:ran, :ran, :ran]
iex> Enum.to_list(tracked) # same recipe, run again
[1, 2, 3]
iex> flush()
[:ran, :ran, :ran] # six total, not three
Materialize once if you need the elements twice:
elements = Enum.to_list(tracked) # side effects happen exactly once, here
Caveat worth knowing: streams built from generators rather than
collections are single-pass and cannot be re-enumerated at all. You
will meet this with file handles and Stream.resource — the after-hook
has already closed the device.
From Erlang you know: this is the difference between a list you hold and a computation you describe. In Erlang you rarely had to think about it because
lists:map/2always gave you the list. The Elixir discipline that transfers: materialize at a boundary (when you cross from description to use), and stay lazy inside a single expression.
Laziness Is Not Automatically Faster
The opposite trap deserves equal billing. Over a finite collection with a
consumer that needs everything, laziness buys you little in speed: it replaces
an intermediate list with a closure and an extra protocol dispatch per element.
On a 100k-element map |> sum, eager Enum and lazy Stream land within
run-to-run noise of each other:
n = 1..100_000
Enum.sum(Enum.map(n, &(&1 * 2))) # eager: allocates the mapped list first
Enum.sum(Stream.map(n, &(&1 * 2))) # lazy: no intermediate list, more overhead
So do not reach for Stream expecting raw speed. Reach for it for one of
three real reasons: avoiding the intermediate allocation on a large
collection, terminating early, or consuming an unbounded source or an
external handle. Everything else is Enum, and the ergonomic default should
be too.
The flip side: laziness composes with concurrency when the source is
task-shaped. Task.async_stream/3 returns a stream that only launches work as
the consumer pulls, but it does overshoot — verified: ten items,
max_concurrency: 4, Enum.take/2 returns 3 results and starts 6 tasks.
async_stream keeps its pool full, so it launches ahead to
max_concurrency plus whatever is already in flight, then the puller stops
it. Work you hoped was skipped has already run.
This is the right mental model, and it generalizes: lazy ≠ “no work
happened.” It means “no work happens past the point you stopped pulling.”
Anything a stream function does as a side effect before its emit point has
already happened. Bounded fan-out (§28.4) is the pattern that gets you a real
bound.
4.4 Choosing Between Them
| Situation | Use |
|---|---|
| Small/medium collections, simple transforms | Enum (eager) |
| Large datasets, file/IO streams | Stream |
| Composing transformations across function boundaries | Stream |
| You need results more than once | Materialize once into a list |
| Nx tensor pipelines (Part IV) | Neither — tensors batch natively |
Rule of thumb: eager by default, lazy when memory or composition matters.
A useful heuristic from practice: if a pipeline touches files, network
responses, or anything unbounded, start with Stream; otherwise Enum’s
simplicity wins.
One warning worth internalizing early: calling Enum.* on a stream
materializes it — that’s the design (streams are consumed by eager
functions), but accidentally interleaving an Enum.map mid-chain silently
turns your lazy pipeline eager up to that point.
Measure It: Two Minutes, Permanent Intuition
Do not take laziness on faith — :timer.tc/1 tells the story on your own
hardware:
eager = fn ->
1..5_000_000 |> Enum.map(&(&1 * 2)) |> Enum.filter(&rem(&1, 3) == 0)
|> Enum.take(5)
end
lazy = fn ->
1..5_000_000 |> Stream.map(&(&1 * 2)) |> Stream.filter(&rem(&1, 3) == 0)
|> Enum.take(5)
end
{t_eager, r1} = :timer.tc(eager) # microseconds
{t_lazy, _r2} = :timer.tc(lazy)
r1
#=> [6, 12, 18, 24, 30] # identical results…
IO.puts("eager #{div(t_eager, 1000)}ms vs lazy #{div(t_lazy, 1000)}ms")
#=> eager ~190ms vs lazy ~0ms # …but lazy stops after five matches
For memory, sample :erlang.memory(:processes) before and after each
variant, or run :observer.start() and eyeball the per-process graph.
Numbers beat doctrine — especially before imposing Stream on a hot path
where per-element closures would cost more than they save.
4.5 Streams Are Everywhere in the Ecosystem
You will meet Stream again in this book:
- Nx batching:
Nx.to_batched(tensor, size)returns a lazy stream of batches (Ch 19). - LLM streaming: token chunks arrive as a
Stream.resource(Ch 28). - Broadway/GenStage: dataflow pipelines are stream-shaped (Ch 13).
Explore More
- Enum docs — skim the full function list once; knowing what exists saves reinventions
- Stream docs — especially
resource/3, the bridge from any external source to a lazy sequence - Comprehensions guide —
reduce:options and binary generators - Erlang Efficiency Guide: lists
— the same trade-offs written for
lists:, including whenlists:foldlbeats building intermediates - Exercise: take an eager pipeline from your own code, convert to
Stream, and measure memory with:erlang.memory(:processes)before/after on large input — feel the difference instead of believing it - Exercise: reproduce §4.3’s short-circuit proof with an
IO.putsside effect (eager prints 3, 4, 5 and discards them; lazy never does), then reproduce theTask.async_streamovershoot — count tasks that actually started when youEnum.take/2fewer than you asked for - Integration exercise: read a large log file with
File.stream!/1, trim and filter lines lazily, fan the expensive ones out throughTask.async_stream(..., max_concurrency: 8), and fold the results withEnum.reduce— the whole shape of this chapter in one pipeline
Checkpoint
- Convert
lists:foldlaccumulation over filtered input into a pipe chain. - When does a
Streampipeline actually execute? - Why is
Streamsafer than eager chains on unbounded input? - What’s the difference between
then/2andtap/2in a pipe? - How do you iterate
1..10by twos? - When
Enum.map/2walks a map, what shape arrives at your function? - You write
Enum.map(1..1000, side_effect) |> Enum.take(2). How many times doesside_effectrun, and why is the number surprising? - You enumerate the same
Streamtwice with differentEnumfunctions. What happens to the side effects inside it?
Answers
input |> Enum.filter(pred) |> Enum.reduce(acc, fun)- When a reduction-hungry
Enumfunction consumes it (to_list,take,sum,each,run…). - It pulls element-by-element with constant memory and short-circuits on
take-style termination, so unbounded sources never blow the heap. thencontinues the pipe with the function’s return value;tapruns a side effect and passes the original value through.1..10//2— a stepped range (Enum.to_list(1..10//2)→[1, 3, 5, 7, 9]).{key, value}tuples — maps implementEnumerable, so nomaps:to_list/1conversion step is needed.- All 1000.
Enum.mapis eager: it builds the whole list, and only then doestake/2keep two elements. The other 998 results were computed and discarded.Stream.mapwould run it twice. - They run twice. A
Streamis a recipe, not a cache — every enumeration re-executes every step. Materialize withEnum.to_list/1once if you need the elements more than once, and remember generator-backed streams (file handles,Stream.resource) are single-pass and cannot be re-run at all.