anna2000
anna2000

Reputation: 25

Elixir function calling in a loop with 2 parameters

Is it possible in Elixir to call a function i times with 2 parameters? It would look line this in Java:

List myList = new ArrayList();
for(int i=1; i<10; i++) {
   myList.addAll(doSomething(other_list,i))
}

Upvotes: 0

Views: 416

Answers (3)

Thomas
Thomas

Reputation: 2952

In functional programming, you have to treat data differently. You send the data through, process it, and get the data back. In Java, you wanted to store each iteration in an outside loop, in Elixir, you just want to interact with the data (process it) and then spit it out. To do this, you want to use the Enum.map approach. This will return a list of data that each iteration spit out.

For instance:

iex(3)> Enum.map(1..9, &(&1 + 1))
[2, 3, 4, 5, 6, 7, 8, 9, 10]

so for your function

defmodule Something do
  def do_something(index) do
    index + 1
  end
end

will return this in iex:

iex(7)> Enum.map(1..9, fn index ->
...(7)>   Something.do_something(index)
...(7)> end)
[2, 3, 4, 5, 6, 7, 8, 9, 10]

The major thing here is understanding the difference between Functional and OOP programming. The major difference is the way data is handled. Which is explained well here

Upvotes: 1

sabiwara
sabiwara

Reputation: 3159

The most straightforward way would be to use Enum.map/2:

Enum.map(1..9, fn i -> do_something(other_list, i) end)

Or a for comprehension:

for i <- 1..9, do: do_something(other_list, i)

That being said, it really depends on what do_something is doing. Elixir lists are linked lists: if you plan to access the ith element inside the "loop", your time complexity will be quadratic. You probably would need to rethink your approach to work on elements rather than the list, Enum.with_index/2 should help:

other_list
|> Enum.take(10)
|> Enum.with_index(1, &do_something/2)

Upvotes: 3

Aetherus
Aetherus

Reputation: 8898

Basing on your Java code, I suppose doSomething(otherList, i) returns a list. If so, then you can use Enum.flat_map in Elixir, like this:

Enum.flat_map(1..9, fn i ->
  do_something(other_list, i)
end)

Upvotes: 1

Related Questions