I discovered a pretty cool Elixir function this weekend,
Backstory: I wanted to group a list of strings by equality, while preserving the list order.
Enum.chunk_by takes an enumerable and a function, and breaks that enumerable into an enumerable when the function returns a new or different result.
Here's a simple example:
iex> Enum.chunk_by(['A', 'A', 'A', 'B', 'A'], fn(l) -> l end) [['A', 'A', 'A'], ['B'], ['A']]
l changes, a new list is created.
Slightly more complex:
iex> Enum.chunk_by([1, 2, 3, 4, 5], fn(n) -> rem(n, 3) == 0 end) [[1, 2], , [4, 5]]
The function only returns something different (
3 is assigned to its own list.