I can't understand how to iterate with index in Elixir.
For example, I have this snippet from java and I want to translate it into Elixir:
for(int i = 1; i < list.size(); i++) {
list.order = i;
}
Lets say that list
is a list of maps from Elixir.
I can't understand how to do this either in Elixir way or just iterate with some index variable.
To iterate over a Map, we can use for..of and forEach() loop constructs. Map provides three methods that return iterable: map. keys(), map. values() and map.
Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.
In Elixir, to loop through a range, you need to use recursion. Recursion is the method of making a function call itself until a base-case is reached.
While the answer by Justin is perfectly valid, the idiomatic Elixir solution would be to use Enum.with_index/2
:
list = ~w|a b c d e|
list
|> Enum.with_index()
|> Enum.each(fn {e, idx} -> IO.puts "Elem: #{e}, Idx: #{idx}" end)
#⇒ Elem: a, Idx: 0
#⇒ Elem: b, Idx: 1
#⇒ Elem: c, Idx: 2
#⇒ Elem: d, Idx: 3
#⇒ Elem: e, Idx: 4
When working with a language that doesn't allow mutation of data, it's not so straightforward as iterating over a collection and setting values. Instead, you need to create a new collection with new objects that have your field set.
In Elixir, you can do this with a foldl
:
List.foldl(
list,
(1, map),
fn(l, (i, map)) -> (i+1, Map.update(map, :some_key, $(i)))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With