rrrr

rrrr

How to "merge" / "map" two sparse maps into one?

What is Elixir way to “merge” / “map” two sparse maps onto one? I want to apply some function on both or single value from these maps. By “sparse” i mean that some keys are missing in another map. Like
a = %{1=>1, 2=>2, 4=>4}
b = %{0=>0, 1=>11, 2=>22, 5=>55}
looking for c=%{0=>f(0), 1=>f(1,11), …}

So far I have come with obtaining list of common keys and moving with it as index for both maps.

Closest built-in solution was Map.merge(map1, map2, fun), but it does not cover custom behavior when key is missing in one map.

Can solution be Stream’able?
Should I look for some non-default library?

Marked As Solved

LostKobrakai

LostKobrakai

Map.new(Map.keys(a) ++ Map.keys(b), fn key -> 
  case {Map.fetch(a, key), Map.fetch(b, key)} do
    {:error, {:ok, val}} -> {key, f(val)}
    {{:ok, val}, :error} -> {key, f(val)}
    {{:ok, val_a}, {:ok, val_b}} -> {key, f(val_a, val_b)}
    # {:error, :error} not possible
  end
end)

Also Liked

Sorc96

Sorc96

Can you merge the maps first and then apply the function?

Map.merge(a, b, fn _key, value1, value2 -> {value1, value2} end)
|> Map.new(fn
  {key, {value1, value2}} -> {key, f(value1, value2)}
  {key, value} -> {key, f(value)}
end)

It could get a bit cleaner if Elixir had an equivalent of Ruby’s transform_values, then it wouldn’t be necessary to repeat the key manually.

I’m guessing you want to use Stream because of t hef function? In that case I think you could first use Stream.map and then convert the result back into a map.

hlx

hlx

map1 = %{a: 1, b: 2}
map2 = %{b: 1, c: 1}
fun = fn x, y -> x + y end

for {k1, v1} <- map1, {k2, v2} <- map2, reduce: %{} do
  acc ->
    if k1 == k2 do
      Map.put(acc, k1, fun.(v1, v2))
    else
      acc
      |> Map.put(k1, v1)
      |> Map.put(k2, v2)
    end
end

edit: after reviewing it myself this is not a great solution.

LostKobrakai

LostKobrakai

This one iterates map2 for each key/value pair in map1. That can become expensive rather quickly.

BradS2S

BradS2S

a = %{1=>1, 2=>2, 4=>4}
b = %{0=>0, 1=>11, 2=>22, 5=>55}
c = %{}
keys = Map.merge(a, b) |> Map.keys

for key ← keys do
case {Map.take(a, [key]), Map.take(b, [key])} do
{a_value, b_value} when map_size(b_value) == 0 → Map.put(c, key, f.(a_value))
{a_value, b_value} when map_size(a_value) == 0 → Map.put(c, key, f.(b_value))
{a_value, b_value} → Map.put(c, key, ff.(a_value, b_value))
end
end

Would something like this work?

LostKobrakai

LostKobrakai

I think you’ll get (k1+k2) *2 only if you can make sure non of the map values is whatever you store in the map as an intermediate representation for “there were matching keys with two separate values”.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
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
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

We're in Beta

About us Mission Statement