Elixir Enum Basics
Enum is a module that provides functions for working with collections such as lists and ranges. Its basic functions answer questions about a whole collection, such as how many items it holds.
Count works on lists and ranges
Enum.count counts the items in a list and in a range. Enum.empty? separates the empty list from the full one.
numbers = [150, 220, 310, 480]
IO.puts(Enum.count(numbers))
IO.puts(Enum.count(1..7))
IO.puts(Enum.empty?([]))
IO.puts(Enum.empty?(numbers))Membership and sum give exact answers
Enum.member? finds 400 in the price list but not 999. Enum.sum totals the list and the range 1..100.
prices = [250, 400, 150]
IO.puts(Enum.member?(prices, 400))
IO.puts(Enum.member?(prices, 999))
IO.puts(Enum.sum(prices))
IO.puts(Enum.sum(1..100))Min, max, any, and all describe a list
The smallest score is 61 and the largest is 95. One score reaches 90, every score reaches 60, but not every score reaches 70.
scores = [72, 95, 61, 88]
IO.puts(Enum.min(scores))
IO.puts(Enum.max(scores))
IO.puts(Enum.any?(scores, fn s -> s >= 90 end))
IO.puts(Enum.all?(scores, fn s -> s >= 60 end))
IO.puts(Enum.all?(scores, fn s -> s >= 70 end))Example
items = [120, 340, 85, 260]
IO.puts(Enum.count(items))
IO.puts(Enum.sum(items))
IO.puts(Enum.max(items))
IO.puts(Enum.member?(items, 85))
IO.puts(Enum.any?(items, fn price -> price > 300 end))Key points
- Enum module: Enum holds functions that read lists, ranges, and other collections.
- Count: Enum.count returns how many items a collection holds.
- Empty check: Enum.empty? returns true only when a collection holds no items.
- Membership: Enum.member? returns true when a value is in the collection.
- Sum: Enum.sum adds up a collection of numbers.
- Extremes: Enum.min returns the smallest value in a collection, and Enum.max returns the largest.
- Predicate checks: Enum.any? and Enum.all? run a test function over the items of a collection.
In this example, Enum.count reports 4 items in the list. Enum.sum totals them to 805 and Enum.max finds the largest price, 340. Enum.member? confirms 85 is present, and Enum.any? confirms at least one price is above 300.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Enum.sum(1..4) return?