Skip to content

Instantly share code, notes, and snippets.

@dimitarvp
Created October 24, 2024 21:37
Show Gist options
  • Save dimitarvp/5b7a3589633d1f84d2bdd75139133f04 to your computer and use it in GitHub Desktop.
Save dimitarvp/5b7a3589633d1f84d2bdd75139133f04 to your computer and use it in GitHub Desktop.
An Elixir module with a single function demonstrating an `Enum.zip` implementation with wrap-around of the second list argument.
defmodule Lists
@doc """
Works similarly to `Enum.zip/2` but it also wraps around the second list parameter,
for example `zip_cycle([1, 2, 3, 4], [:x, :y, :z])` yields `[{1, :x}, {2, :y}, {3, :z}, {4, :x}]`.
It never produces more items than the length of the first list.
"""
def zip_cycle([h0 | t0] = _l0, [h1 | t1] = l1),
do: zip_cycle(t0, t1, l1, [{h0, h1}])
def zip_cycle(_l0, _l1), do: []
defp zip_cycle([h0 | t0], [h1 | t1], l1, acc),
do: zip_cycle(t0, t1, l1, [{h0, h1} | acc])
defp zip_cycle([h0 | t0], [], [h1 | t1] = l1, acc),
do: zip_cycle(t0, t1, l1, [{h0, h1} | acc])
defp zip_cycle([], _, _, acc),
do: :lists.reverse(acc)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment