jonnifyelixir
F2 / F2.05 / filter

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

input kept


      
&(rem(&1, 2) == 0) · [1, 2, 3, 4, 5, 6] → [2, 4, 6] · 3 kept, 3 dropped

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]



      
keep even · [1, 2, 3, 4] → filter → [2, 4] → map ×10 → [20, 40]

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.