Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through the list of maps in Elixir?

Tags:

elixir

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.

like image 709
Irvin Bridge Avatar asked Dec 29 '17 16:12

Irvin Bridge


People also ask

Can you iterate through a map?

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.

Can you iterate through a list?

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.

How do you make a loop in Elixir?

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.


2 Answers

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
like image 95
Aleksei Matiushkin Avatar answered Oct 06 '22 23:10

Aleksei Matiushkin


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)))
)
like image 45
Justin Niessner Avatar answered Oct 07 '22 00:10

Justin Niessner