Irvin Bridge
Irvin Bridge

Reputation: 313

How to iterate through the list of maps in 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.

Upvotes: 7

Views: 7655

Answers (3)

maz
maz

Reputation: 8336

Or use a for comprehension

[debug] localized_titles %{attributes: [%{"en" => "The English Title of a Playlist"}, %{"fr" => "Le French Title of a Playlist"}]}

      maps =
        for title <- localized_titles,
            _ = Logger.debug("title #{inspect(%{attributes: title})}"),
            {k, v} <- title do
          IO.puts "#{k} --> #{v}"

          Repo.insert(%PlaylistTitle{language_id: k, localizedname: v, uuid: Ecto.UUID.generate(), playlist_id: playlist.id})
        end
      Logger.debug("maps #{inspect(%{attributes: maps})}")
      {:ok, maps}

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Upvotes: 15

Justin Niessner
Justin Niessner

Reputation: 245419

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

Upvotes: 3

Related Questions