Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Last active November 12, 2022 17:56
Show Gist options
  • Save nathan-cruz77/586092fa2487da2bdd5603934e7db4ad to your computer and use it in GitHub Desktop.
Save nathan-cruz77/586092fa2487da2bdd5603934e7db4ad to your computer and use it in GitHub Desktop.
Equivalent to python's zip_longest function for elixir.
defmodule Zip do
@doc """
Zips corresponding elements from a finite collection of enumerables into one list of tuples.
The zipping finishes when the longest enumerable is finished. Default padding value is `nil`.
Usage:
iex> Bla.zip_longest([1, 2, 3], [1, 2])
[{1, 1}, {2, 2}, {3, nil}]
iex> Bla.zip_longest([1, 2], [1, 2, 3])
[{1, 1}, {2, 2}, {nil, 3}]
"""
def zip_longest([h1 | next1], [h2 | next2]) do
[{h1, h2} | zip_longest(next1, next2)]
end
def zip_longest([h1 | next1], []), do: [{h1, nil} | zip_longest(next1, [])]
def zip_longest([], [h2 | next2]), do: [{nil, h2} | zip_longest([], next2)]
def zip_longest([], []), do: []
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment