I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. I’ve managed to do this using the following code:
def indexed_map(list, index \\ 1, step \\ 1) do
to_indexed_map(list, index,step, %{})
end
defp to_indexed_map([h|t], i, s, acc),do: to_indexed_map(t, i + s, s, Map.put(acc, i, h))
defp to_indexed_map([], _, _, acc), do: acc
Basically if I apply this function to
[100, 200, 300]
it will return
%{1 => 100, 2 => 200, 3 => 300}
Is there any way to the same using Elixir’s standard library? I tried Enum.map, Enum.reduce and even Enum.map_reduce but I just couldn’t figure out how to it using them.
Or shorter (by actually creating the tuple in-order instead of needing to swap it and not getting the length of a list, which can be O(n) instead of O(1)):
An aside, I wish 0.. was a shortcut for (Stream.iterate(0, &(&1+1)), or maybe 0...1 means (Stream.iterate(0, &(&1+1)) like 0...-4 means (Stream.iterate(0, &(&1-4)) or so, ah well I wish, but it does not for now. Hmm, lot of ideas popping into mind for such a syntax, we need a Stream.seq/1.