HiroiImanishi

HiroiImanishi

I'd like to take the element of the same index from multiple lists

Is there a way to take multiple lists and get all the elements at their n th index and pass them to the function?
For example, list1 (= [1,3,5]) and list2 (= [2,4,6]) are added,then list (=[3,7,11]) is created.
What I wrote below is wrong, but I imagine such usage.

defmodule TwoLists do
  def sum(list1,list2) do
    Enum.map(list1,list2,fn(a,b)->a+b end) 
  end
end

iex> list1 = [1,3,5]
iex> list2 = [2,4,6]
iex> TwoLists.sum(list1,list2)
#-->Enum.map/3 is undefined error

I’d like you to show me the way to implement.
Thanks

Marked As Solved

domvas

domvas

One way I see is the following one:

defmodule ListSum do
  def sum(list1, list2, total \\ [])

  def sum([], [], total) do
    Enum.reverse(total)
  end

  def sum([h1 | t1], [], total) do
    sum(t1, [], [h1 | total])
  end

  def sum([], [h2 | t2], total) do
    sum([], t2, [h2 | total])
  end

  def sum([h1 | t1], [h2 | t2], total) do
    sum(t1, t2, [h1 + h2 | total])
  end
end

This implementation has the advantage to work with list of different lengths.
You can also code an implement using for and Enum.at but lists must have same length is this case

Also Liked

kokolegorille

kokolegorille

You might use Enum.zip.

iex(1)> list1 = [1,3,5]
[1, 3, 5]
iex(2)> list2 = [2,4,6]
[2, 4, 6]
iex(3)> Enum.zip list1, list2
[{1, 2}, {3, 4}, {5, 6}]
iex(4)> list3 = [2,4,6,8]    
[2, 4, 6, 8]
iex(5)> Enum.zip list1, list3
[{1, 2}, {3, 4}, {5, 6}]

but it will return a number of elements corresponding to the smallest list in case they are not the same length.

You can use more than two lists

iex(6)> Enum.zip [list1, list2, list3]
[{1, 2, 2}, {3, 4, 4}, {5, 6, 6}]

And for your use case…

iex(7)> list1 |> Enum.zip(list2) |> Enum.map(& (elem(&1, 0) + elem(&1, 1)))
[3, 7, 11]
hauleth

hauleth

This is terrible solution, because Enum.at/2 has linear complexity. So in your case the complexity of this function is quadratic instead of linear.

joaoevangelista

joaoevangelista

the function without the do block is a header function, it is needed when we declare default arguments on matching functions, see that only that function has the total with a default value. Without it you would get a definitions with multiple clauses and default values require a header. error message from the compiler.
Roughly the compiler will create a sum/2 function calling the matching functions sum/3 with a default value on the third argument.

You can see more examples at Elixir School.

:smile:

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
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
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement