rms.mrcs
Transform a list into an map with indexes using Enum module
Hi,
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.
Thanks
Marked As Solved
Linuus
Something like this should work:
list = [100, 200, 300]
Stream.with_index(list, 1) |> Enum.reduce(%{}, fn({v,k}, acc)-> Map.put(acc, k, v) end)
Or this ![]()
1..length(list) |> Stream.zip(list) |> Enum.into(%{})
Also Liked
andre1sk
There is prob a better way then this:
list |> Enum.with_index(1) |>Enum.map(fn {k,v}->{v,k} end) |> Map.new
OvermindDL1
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)):
iex> list = [:a,:b,:c,:d,:e]
iex> Stream.zip(Stream.iterate(0, &(&1+1)), list) |> Enum.into(%{})
%{0 => :a, 1 => :b, 2 => :c, 3 => :d, 4 => :e}
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








