xgeek116

xgeek116

Fill a list after Enum.Each Loo^p

I’m trying to fill a list from the result of many loops (iterating another list) but the result is always empty here is my code :

list_a = []
list_b =  []
        Enum.each(list_c, fn(item) ->
          {item_a, item_b} = process(item)
          list_a ++ item_a.inner_list
          list_b ++ item_b.inner_list
        end)

For each iteration, item_a and item_b have a list named inner_list, so I tried to concatenate each time that list with the result lists but list_a and list_b are always empty.

Thanks in advance

Marked As Solved

al2o3cr

al2o3cr

Like @LostKobrakai mentioned, scoping is one problem: code inside a do block can’t rebind variables outside of that block in a way that’s visible outside.

The other problem is that ++ makes a new list, it doesn’t mutate either argument. Code like what you posted is pretty common in other languages:

# in Ruby
list_a = []
list_b = []

list_c.each do |item|
  item_a, item_b = process(item)
  list_a.concat(item_a.inner_list)
  list_b.concat(item_b.inner_list)
end
# in Python
list_a = []
list_b = []

for item in list_c:
  item_a, item_b = process(item)
  list_a.extend(item_a.inner_list)
  list_b.extend(item_b.inner_list)

This approach will not work in Elixir. My suggestion is that you temporarily forget you even saw Enum.each; it’s only useful in a very narrow set of situations.


A better way to think about solving these kinds of problems in Elixir is to focus on how the “shape” of the data changes.

As a first step, we want to run process/1 on every element of list_c:

processed_list = Enum.map(list_c, &process/1)

Each element of processed_list is a tuple shaped like {item_a, item_b}.


There are several possibilities here: we could refine these tuples by extracting inner_list, but instead we’ll start by regrouping them.

What we have is a list of 2-element tuples.
What we want is a 2-element tuple of lists (what the original called list_a and list_b)

This kind of transformation comes up often enough that it has a name: Enum.unzip/1. Using it looks like:

tuple_of_lists = Enum.unzip(processed_list)

Now tuple_of_lists is shaped like {list_of_item_as, list_of_item_bs}


Finally, we need to extract the inner_list parts. We could use Enum.map again:

# not quite right - see below for a correct solution
{list_of_as, list_of_bs} = tuple_of_lists
list_a = Enum.map(list_of_as, & &1.inner_list)
list_b = Enum.map(list_of_bs, & &1.inner_list)

but this doesn’t quite do what we’re looking for: it results in list_a and list_b being lists of lists. You could use List.flatten/1, if the values in inner_list are not themselves lists.

BUT

There’s an easier way! Again, what we’re looking for is referenced enough to have a name: Enum.flat_map:

{list_of_as, list_of_bs} = tuple_of_lists
list_a = Enum.flat_map(list_of_as, & &1.inner_list)
list_b = Enum.flat_map(list_of_bs, & &1.inner_list)

Putting all the pieces together gives this code:

processed_list = Enum.map(list_c, &process/1)

tuple_of_lists = Enum.unzip(processed_list)

{list_of_as, list_of_bs} = tuple_of_lists
list_a = Enum.flat_map(list_of_as, & &1.inner_list)
list_b = Enum.flat_map(list_of_bs, & &1.inner_list)

This code can be tidied up with some Elixir syntax goodies:

# squish "processed_list" out of existence since it is bound and then immediately used
tuple_of_lists =
  list_c
  |> Enum.map(&process/1)
  |> Enum.unzip()

{list_of_as, list_of_bs} = tuple_of_lists
list_a = Enum.flat_map(list_of_as, & &1.inner_list)
list_b = Enum.flat_map(list_of_bs, & &1.inner_list)

and even more with then which was recently added:

{list_a, list_b} =
  list_c
  |> Enum.map(&process/1)
  |> Enum.unzip()
  |> then(fn {list_of_as, list_of_bs} ->
    {
      Enum.flat_map(list_of_as, & &1.inner_list),
      Enum.flat_map(list_of_bs, & &1.inner_list)
    }
  end)

This code does exactly the same steps as the first “un-simplified” version, but avoids having to name a bunch of variables that are used exactly once (like processed_items and tuple_of_lists).

Also Liked

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement