defmodule Example do
def to_indexed_map(list, offset \\ 0)
when is_list(list)
and is_integer(offset),
do: for {v, k} <- list |> Enum.with_index,
into: %{},
do: {k+offset, v}
endExample usage:
iex> list = ~w[dog cat sheep]
["dog", "cat", "sheep"]
iex> Example.to_indexed_map(list)
%{0 => "dog", 1 => "cat", 2 => "sheep"}Minor Update: A less concise, but more performant version (roughly 2x faster) is shown below.
defmodule Example do
def to_indexed_map(list, offset \\ 0)
when is_list(list)
and is_integer(offset),
do: to_indexed_map(list, offset, [])
defp to_indexed_map([], _k, acc),
do: :maps.from_list(acc)
defp to_indexed_map([v | vs], k, acc),
do: to_indexed_map(vs, k+1, [{k, v} | acc])
end