📎 Webclip
Elixir Stream Patterns
The post looks at several Elixir examples and notes that Streams are not widely used. It compares Stream-based code with ranges, comprehensions, and Enum-based alternatives, and favors the clearest expression for the task.
Reading notes#
- Bmark uses
Stream.repeatedly/1withStream.take/1to run a function multiple times without a mutable counter. - That pattern suggests the function can produce different results on repeated calls.
- Using a range with
maprequires wrapping a zero-arity function, which reduces readability. - A comprehension is presented as a cleaner alternative to
Stream.repeatedly(f) |> Stream.take(count). - ExUnit’s
ExUnit.DocTestusesStream.filterandStream.with_indexin a pipeline that ends withEnum.map. - The post questions why
Streamis used there instead ofEnum, sinceEnum.mapeagerly consumes the result. - In
Mix.Utils,stale_streamfeeds bothstale?andextract_stale. stale?can stop early withEnum.any, whileextract_staleneeds the full list of stale files.- That example shows how lazy evaluation can save work when only the first matching element matters.
- The closing advice is to experiment with Elixir’s syntax and choose the most expressive form for the code at hand.
