vmg

vmg

Zip list of different lengths

I’m having trouble trying to zip lists of different lengths because elixir only returns the first match of each list.

I have the following list of lists:

[
  ["e5", "e7", "e7", "e8", "e8", "e2", "e2", "e0", "e0", "e0"],
  ["B5", "B5", "B5", "B3", "B1", "B1", "B1", "B0", "B1", "B1"],
  ["G5", "G5", "G5", "G2", "G2", "G2"],
  ["D7"]
]

Elixir return this:
[{“e5”, “B5”, “G5”, “D7”}]

And I would like to get the following list:

[
  ["D7", "G5", "B5", "e5"],
  ["G5", "B5", "e7"],
  ...,
  ["B1", "e0"]
]

Is there any way to accomplish this with zip or any other function?

Most Liked

Sebb

Sebb

not directly possible.

The zipping finishes as soon as any enumerable in the given collection completes. [Enum — Elixir v1.16.0]

Sth like python’s zip_longest would be nice in Enum.
But even that would leave you with some handy work.

Hint: you could pad the lists with nil to fill all up to length of the longest list, and then remove the nils after that.

dimitarvp

dimitarvp

If you don’t want to write your own recursive function helpers for this then your best bet is indeed filling up the smaller lists with a marker value – nil or something else – and then just throw those away after the zipping operation, as @Sebb suggested.

akash-akya

akash-akya

@dimitarvp already suggested recursion, this is one way to do that using unfold

data = [
  ["e5", "e7", "e7", "e8", "e8", "e2", "e2", "e0", "e0", "e0"],
  ["B5", "B5", "B5", "B3", "B1", "B1", "B1", "B0", "B1", "B1"],
  ["G5", "G5", "G5", "G2", "G2", "G2"],
  ["D7"]
]

Stream.unfold(data, fn list_of_list ->
  List.foldr(list_of_list, {[], []}, fn
    [], {heads, tails} -> {heads, tails}
    [h], {heads, tails} -> {[h | heads], tails}
    [h | t], {heads, tails} -> {[h | heads], [t | tails]}
  end)
  |> case do
    {[], _tails} -> nil
    {heads, tails} -> {heads, tails}
  end
end)
|> Enum.to_list()
Sebb

Sebb

  def zip([], zipped), do: zipped

  def zip(lists, zipped) do
    {zipped_, rest_} =
      for [h | t] <- lists, reduce: {[], []} do
        {hs, ts} -> {[h | hs], ts ++ [t]}
      end

    zip(Enum.reject(rest_, &(&1 == [])), zipped ++ [zipped_])
  end
zip(data, []) #=> [
  ["D7", "G5", "B5", "e5"],
  ["G5", "B5", "e7"],
  ["G5", "B5", "e7"],
  ["G2", "B3", "e8"],
  ["G2", "B1", "e8"],
  ["G2", "B1", "e2"],
  ["B1", "e2"],
  ["B0", "e0"],
  ["B1", "e0"],
  ["B1", "e0"]
]

or using Enum.zip with help

  def zip2(lists) do
    max_len = lists |> Enum.map(&length(&1)) |> Enum.max()

    lists
    |> Enum.map(&(&1 ++ List.duplicate(nil, max_len - length(&1))))
    |> Enum.zip()
    |> Enum.map(& &1 |> Tuple.to_list() |> Enum.reject(fn x -> x == nil end))
  end
Eiji

Eiji

Here you go:

defmodule Example do
  def sample(input) do
    input
    |> Enum.reduce({[], []}, fn
      # when list contains only one element
      # we add it as others and skipping empty list in next steps
      [head], {left_acc, right_acc} -> {[head | left_acc], right_acc}
      # in other case
      # we add list's head and pass its tail, so it would be used in next steps
      [head | tail], {left_acc, right_acc} -> {[head | left_acc], [tail | right_acc]}
    end)
    |> case do
      # since we have lists of lists we need to wrap last list in another one-element list
      # so it's added as one, last element of result
      # instead of adding all elements of last list as separate result elements
      # [
      #   list1,
      #   list2,
      #   # …
      #   listn_elem1,
      #   listn_elem2
      # ]
      {left_acc, []} -> [left_acc]
      # left_acc here is a list of heads for each step
      # tail is a recursive call of input lists except their heads
      # we need to reverse it as otherwise each step would have opposite order to previous step
      {left_acc, right_acc} -> [left_acc | right_acc |> Enum.reverse() |> sample()]
    end
  end
end

input = [
  ["e5", "e7", "e7", "e8", "e8", "e2", "e2", "e0", "e0", "e0"],
  ["B5", "B5", "B5", "B3", "B1", "B1", "B1", "B0", "B1", "B1"],
  ["G5", "G5", "G5", "G2", "G2", "G2"],
  ["D7"]
]

iex> Example.sample(input)

Helpful resources:

  1. Enum.reduce/3
  2. Enum.reverse/1

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement