简体   繁体   中英

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.

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM