rrrr

rrrr

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?

Showing Posts 1 to 10

BradS2S

BradS2S

Could you write a function to handle balls without a key and then use it in map.merge?

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.

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?

Sorc96

Sorc96

The function passed into merge only gets called if there is a conflict - both maps have the same key. That is why I thing this needs to be done in two steps. Merge first and resolve conflicts, then apply the function.

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)
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.

rrrr

rrrr OP

I feel this solution will have complexity of k1*k2, but in other solutions it’s something about (k1+k2) *2

adamu

adamu

Map.merge(a, b, fn _k, v1, v2 -> f(v1, v2) end)

edit: ah sorry, this doesn’t run the function if there’s no conflict. Knew it seemed too simple.

rrrr

rrrr OP

this is my current solution but written in a much nicer way =) thank you)

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews