jonnifyelixir
F3 / F3.04 / Enum

F3.04 · part 1 of 3

Enum, the eager workhorse

The Enum module is where most collection work happens. Its functions take any enumerable and a function, walk every element, and return a new collection. It is eager: each call runs to completion and hands back a finished result before the next call begins.

Given a learner's progress — a list of records, each with a course and a completion flag — a handful of Enum functions answer most questions: how many are done, how they group by course, how the statuses break down.

Summarising progress

Here are five progress records across two courses. Choose an Enum operation and see what it computes from them.

Enum operation · select one

PROGRESS · 5 RECORDS RESULT

      

Each function reads the whole list and returns something new — a number, a map, a grouped structure — without changing the records. That is the eager model: compute the full answer now.

The functions you reach for

A small set covers most needs. map transforms, filter selects, reduce accumulates — and the rest, like group_by, frequencies_by, and sort_by, are built on reduce.

# each call returns a brand-new collection
ids       = Enum.map(progress, & &1.lesson_id)
done      = Enum.filter(progress, & &1.completed)
by_course = Enum.group_by(progress, & &1.course)
mix       = Enum.frequencies_by(progress, & &1.completed)

# reduce is the engine the others are built on
count = Enum.reduce(progress, 0, fn r, n ->
  if r.completed, do: n + 1, else: n
end)

F2.05 · the fold

Reduce a collection to a single value by folding each element into an accumulator.

F3 · Enum.reduce

The same fold as a real function — and the base that map, filter, and group_by are written on.

Next: comprehensions — a second way to walk an enumerable and build a collection.

References

Primary sources for this lesson, and where it connects in the course.

Sources

Related in this course