Giezy Ramírez
Giezy Ramírez

Reputation: 91

How can i pass a list as argument for a function element by element in Elixir?

i have a function (lex_raw_tokens) that receives 2 arguments. Another function has 2 lists of elements that i need to pass as arguments to the other function, but element by element.

In the original code the function only received 1 argument and i called it using Enum.flat_map(sal, &lex_raw_tokens/1), sal being the list i'm passing. This worked but later on i had to change lex_raw_tokens to receive 2 arguments instead of 1.

I tried solving the issue with Enum.flat_map(sal, &lex_raw_tokens(&1, line)) and, while this technically works, line gets passed as an entire list instead of individual elements.

I'm still quite new to Elixir and i haven't found any other function to replace flat_map that does what i want and i haven't found a way to use flat_map like this.

I should also mention that the lists i'm passing have a variable lenght so i can't brute force my way around this problem. Also, both lists have the same lenght and have a relation, so I would need to use the first element of sal with the first element of line, the second with the second and so on.

Upvotes: 1

Views: 662

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Enum.zip/2 is your friend here.

sal = ~w|one two three|
line = ~w|apple orange lemon|

sal
|> Enum.zip(line)
|> Enum.flat_map(&lex_raw_tokens(elem(&1, 0), elem(&1, 1)))

Upvotes: 1

Related Questions