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

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
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
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
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
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
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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