rms.mrcs

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

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 :stuck_out_tongue:

1..length(list) |> Stream.zip(list) |> Enum.into(%{})

Also Liked

andre1sk

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

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.

Qqwy

Qqwy

TypeCheck Core Team

You might like the Sequences Hex package that I made a while back. It defines streams for quite a few common numeric sequences. :slight_smile:

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement