Don Metro
Don Metro

Reputation: 25

How can I write an Elixir mapping function such that it can adding items in each list?

how can i apply a map function that takes a function f and 2 list l1 and l2 and returns the list that is produced by applying the function to one element from each of the list in turn?

some pseudocode

function add(a1,a2) {return a1 + a2}

map2(add, [1,2,3], [4,5,6])

And this would produce a list

[5,7,9]

Here is what I've done so far

 Enum.map(list, fn n -> IO.puts n + Enum.each(list2, fn z -> z end)

Upvotes: 0

Views: 1796

Answers (3)

Adzz
Adzz

Reputation: 1579

By way of update in Elixir 1.12 there will be an Enum.zip_with/3 function:

https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/enum.ex#L3349

Upvotes: 0

Dogbert
Dogbert

Reputation: 222118

There's a function in Erlang's lists module which does exactly this: lists:zipwith/3. There's no wrapper for that in Elixir's Enum module though.

iex(1)> :lists.zipwith(fn a, b -> a + b end, [1, 2, 3], [4, 5, 6])
[5, 7, 9]

fn a, b -> a + b end can be shortened to taking a reference to the + operator:

iex(2)> :lists.zipwith(&Kernel.+/2, [1, 2, 3], [4, 5, 6])
[5, 7, 9]

Upvotes: 3

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

I would go with firstly Enum.zip/2ing inputs and then applying the function:

iex(1)> defmodule M do
...(1)>   def add({a1, a2}), do: a1 + a2
...(1)> end
iex(2)> Enum.zip([1,2,3], [4,5,6]) |> Enum.map(&M.add/1)
#⇒ [5, 7, 9]

Or, using a comprehension Kernel.SpecialForms.for/1:

iex(3)> for {i1, i2} <- Enum.zip([1,2,3], [4,5,6]), do: i1 + i2
#⇒ [5, 7, 9]

Upvotes: 0

Related Questions