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"}] 

1 Answer

Use Enum.with_index:

iex(1)> for {value, index} <- Enum.with_index(["a", "b"]), do: {value, index} [{"a", 0}, {"b", 1}] 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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