Lesson 16 of 16

Comprehensions & Streams

Comprehensions

Elixir's for comprehension lets you transform and filter collections concisely:

# Basic comprehension — doubles each element
doubled = for x <- [1, 2, 3, 4], do: x * 2
IO.inspect(doubled)   # [2, 4, 6, 8]

Generators and Filters

A comprehension can have multiple generators (the x <- list part) and filters (boolean expressions):

# Filter: only even numbers
evens = for x <- 1..10, rem(x, 2) == 0, do: x
IO.inspect(evens)   # [2, 4, 6, 8, 10]

Multiple generators produce a cartesian product:

pairs = for x <- [1, 2], y <- [:a, :b], do: {x, y}
# [{1, :a}, {1, :b}, {2, :a}, {2, :b}]

Streams

While Enum functions are eager (they process the entire collection immediately), the Stream module provides lazy evaluation — elements are computed only when needed:

result = [1, 2, 3, 4, 5]
  |> Stream.map(fn x -> x * 2 end)
  |> Stream.filter(fn x -> x > 4 end)
  |> Enum.to_list()
IO.inspect(result)   # [6, 8, 10]

Streams are useful when working with large or infinite data — they avoid creating intermediate lists.

# Stream.take pulls only what's needed
first_five = Stream.iterate(1, fn x -> x + 1 end) |> Enum.take(5)
IO.inspect(first_five)   # [1, 2, 3, 4, 5]

Your Turn

  1. Use a for comprehension to square only the odd numbers from [1, 2, 3, 4, 5]
  2. Use Stream.map and Stream.filter with Enum.to_list to triple numbers and keep those > 6
  3. Use Stream.iterate with Enum.take to get the first 5 powers of 2 starting from 1
JS Transpiler loading...
Loading...
Click "Run" to execute your code.