0

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))
}
1
  • 3
    There is no such thing as a loop in elixir. Also you cannot modify anything in place as in java, everything is immutable. Commented Sep 23, 2022 at 7:58

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Also, using Stream if the intermediate results are out of interest: 1 |> Stream.iterate(&(&1+1)) |> Stream.map(&IO.inspect(&1, label: "#{&1}")) |> Enum.take(10).
1

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.