Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77 nathan-cruz77/zip.ex
Last active Oct 8, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.