🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Enum Transform

Enum transform functions are Enum functions that build a new collection from an existing one. They change, keep, drop, or reorganise items without changing the original collection.

Map changes, filter keeps, reject drops

Map adds 10 to every number in the list. Filter keeps the numbers of 150 or more, and reject drops exactly those numbers.

numbers = [150, 20, 220, 90, 310]
IO.inspect(Enum.map(numbers, fn n -> n + 10 end))
IO.inspect(Enum.filter(numbers, fn n -> n >= 150 end))
IO.inspect(Enum.reject(numbers, fn n -> n >= 150 end))

Take, drop, uniq, and join reshape a list

Take and drop split the word list at two items. Uniq removes the repeated words, and join links the result with dashes.

words = ["kiwi", "plum", "kiwi", "fig", "plum"]
IO.inspect(Enum.take(words, 2))
IO.inspect(Enum.drop(words, 2))
IO.inspect(Enum.uniq(words))
IO.puts(Enum.join(Enum.uniq(words), "-"))

Zip pairs items, find locates one, chunk groups them

Zip pairs each name with the score in the same position. Find returns 300, the first score above 260, and chunk_every groups the scores in twos.

names = ["Ana", "Bo", "Cy"]
scores = [300, 250, 275]
IO.inspect(Enum.zip(names, scores))
IO.puts(Enum.find(scores, fn s -> s > 260 end))
IO.inspect(Enum.chunk_every(scores, 2))

Example

visits = ["home", "cart", "home", "help", "cart", "home"]
IO.inspect(Enum.frequencies(visits))
words = ["ant", "bear", "cat", "horse"]
IO.inspect(Enum.group_by(words, fn w -> String.length(w) end))

Key points

  • Map: Enum.map applies a function to every item and collects the results.
  • Filter: Enum.filter keeps only the items its test returns true for.
  • Reject: Enum.reject drops the items its test returns true for.
  • Take and drop: Enum.take returns the first items of a collection, and Enum.drop skips them.
  • Unique: Enum.uniq removes duplicate items and keeps the first copy of each.
  • Finding: Enum.find returns the first item that passes its test.

In this example, Enum.frequencies counts how often each page name appears in visits. Enum.group_by then gathers the words by their length. The three-letter words land together under the key 3, while bear and horse sit alone under 4 and 5.

Note

transform functions return new collections, so the original collection stays unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Enum.map([2, 3], fn n -> n * n end) return?