Last active
November 12, 2022 17:56
-
-
Save nathan-cruz77/586092fa2487da2bdd5603934e7db4ad to your computer and use it in GitHub Desktop.
Equivalent to python's zip_longest function for elixir.
This file contains 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 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