Created
March 15, 2022 05:39
-
-
Save bfolkens/f2130521a97c7a994b5c7f66190a0c55 to your computer and use it in GitHub Desktop.
Collate a list of lists in sequence until the longest list is exhausted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Util.Enum do | |
@doc ~S""" | |
Collates a list of lists in sequence until the longest | |
list is exhausted. | |
## Examples | |
iex> Util.Enum.collate([[1, 2, 3], [1, 2], [1, 2, 3, 4]]) | |
[1, 1, 1, 2, 2, 2, 3, 3, 4] | |
iex> Util.Enum.collate([[], [1, 2], [1, 2, 3, 4]]) | |
[1, 1, 2, 2, 3, 4] | |
iex> Util.Enum.collate([[1]]) | |
[1] | |
iex> Util.Enum.collate([[]]) | |
[] | |
iex> Util.Enum.collate([]) | |
[] | |
""" | |
def collate(lists) do | |
lists | |
|> collate([]) | |
|> Enum.reverse() | |
end | |
defp collate(lists, heads) when lists == [], do: heads | |
defp collate(lists, heads) do | |
{heads, tails} = | |
Enum.reduce(lists, {heads, []}, fn | |
[head | tail], {heads, tails} -> | |
{[head | heads], [tail | tails]} | |
[], {heads, tails} -> | |
{heads, tails} | |
end) | |
collate(tails, heads) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment