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:

dimitarvp

dimitarvp

Definitely go with @domvas’ solution. It runs faster and doesn’t break when lists are of different length.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
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
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
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
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

We're in Beta

About us Mission Statement