Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with counter in Elixir

Tags:

elixir

Is there a way to add loop counter to the comprehension?

For example, the comprehension without counter:

for c <- ["a", "b"], do: c            # => ["a", "b"] 

How can I add counter to it? Something like this:

for c <- ["a", "b"], do: {counter, c} # => [{0, "a"}, {1, "b"}] 
like image 845
Alex Craft Avatar asked Mar 10 '16 10:03

Alex Craft


1 Answers

Use Enum.with_index:

iex(1)> for {c, counter} <- Enum.with_index(["a", "b"]), do: {counter, c} [{0, "a"}, {1, "b"}] 
like image 107
Dogbert Avatar answered Oct 06 '22 12:10

Dogbert