Reading — step 1 of 5
Learn
~1 min readCollections
Enum is the everyday module for working with collections — like Ruby's Enumerable or Rust's iterators.
nums = [1, 2, 3, 4, 5]
Enum.map(nums, &(&1 * 2)) # [2, 4, 6, 8, 10]
Enum.filter(nums, &(rem(&1, 2) == 0)) # [2, 4]
Enum.reduce(nums, 0, &+/2) # 15
Enum.sum(nums) # 15
Enum.zip(nums, ["a", "b", "c"]) # [{1, "a"}, {2, "b"}, {3, "c"}]
Enum.group_by([1, 2, 3, 4], &rem(&1, 2)) # %{0 => [2, 4], 1 => [1, 3]}
Stream is the lazy counterpart — operations don't execute until forced (typically with Enum.to_list or Enum.take):
1..1_000_000
|> Stream.map(&(&1 * &1))
|> Stream.filter(&(rem(&1, 7) == 0))
|> Enum.take(5) # forces — only computes what's needed
Use Stream for large or infinite collections. Enum materializes intermediate results; Stream doesn't.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…