What is Elixir's Enum and Stream modules?
Answer
Enum and Stream are Elixir's collection processing modules. Enum: eager evaluation — processes all elements immediately and returns a concrete collection. Enum.map([1,2,3], &(&1 * 2)), Enum.filter, Enum.reduce, Enum.sort, Enum.group_by, Enum.chunk_every. Works with any type implementing the Enumerable protocol. Stream: lazy evaluation — creates a computation pipeline without executing it until needed. Stream.map, Stream.filter, Stream.flat_map. Compose: stream = 1..1_000_000 |> Stream.filter(&(rem(&1, 2) == 0)) |> Stream.map(&(&1 * 2)) |> Stream.take(5); Enum.to_list(stream) — only processes elements until 5 are found, never materializing the entire filtered list. When to use Stream: large or potentially infinite data, reading large files line by line, pipeline stages where you can short-circuit. When to use Enum: small collections where lazy overhead is not worth it.
More Elixir Questions
View all →- Intermediate How do Elixir supervisors implement fault tolerance?
- Intermediate What is Phoenix Channels and how do WebSockets work in Elixir?
- Intermediate What is Elixir's concurrency model compared to threads?
- Intermediate What are Elixir behaviours?
- Intermediate What is Elixir's error handling approach?