F2.05 · part 2 of 4
filter
Filter keeps the elements that pass a test and drops the rest. The predicate — a function returning true or false — decides each element’s fate. Order is preserved; length can only shrink.
Where map transforms every element and keeps the count, filter keeps the values unchanged and
changes the count. Its mirror image is reject, which keeps exactly what filter drops.
And filter composes naturally with map: narrow the list, then transform what remains.
Keep what passes
Filter runs a predicate over each element and keeps only those for which it returns true. The kept elements stay in their original order. Change the predicate and a different subset survives.
Choose the predicate.
- filter
- keep the elements for which a predicate returns true.
- predicate
- a function returning true or false for each element.
- reject
- the inverse of filter — keep where the predicate is false.
- Enum.filter
- Elixir’s filter:
Enum.filter(list, pred).
Enum.filter · pass or drop
Idea
Keep values unchanged, change the count — the opposite trade from map.
F2.05 · reduce
Filter is reduce that appends an element only when the predicate holds.
Filter selects a subset and preserves order. Enum.reject with the same
predicate returns everything filter left behind.
Filter, then map
Filter and map pair up constantly: narrow the list to what you care about, then transform what survives. The filter shrinks the list; the map reshapes the remainder.
Pick the predicate and watch both stages.
filter(pred) then map(&1 * 10) · over [1, 2, 3, 4]
F2.08 · pipelines
Each stage takes a list and returns a list, so they chain with the pipe operator.
Elixir
list |> Enum.filter(p) |> Enum.map(f) reads top to bottom.
Filter before map and you transform fewer elements. The two compose into a clear, linear pipeline.
Worked examples
Filter, its inverse, and the filter-then-map pair — the three you reach for most.