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:

rms.mrcs

rms.mrcs

Thank you :slight_smile:

Linuus

Linuus

The {v, k} is just a pattern match on the values coming in. .with_index returns tuples of the value and the index.

Like this:

Enum.with_index([1,2,3]) => [{100, 1}, {200, 2}, {300, 3}]

So for each value I just destruct the passed in tuple, like {v, k} = {100, 1}.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
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
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement