stevensonmt

stevensonmt

Map.intersection/2?

Has anyone else ever wanted to merge two maps, but have the resulting map only include keys common to both maps? I think of it as analogous to MapSet.intersection but with a function for handling the values.

m1 = %{a: 1, b:2}
m2 = %{b: 3, c:4}
Map.intersection(m1, m2, fn _k, v1, v2 -> v1 * v2 end)
> %{b: 6}

This would replace

Map.merge(m1, m2, fn _k , v1, v2 -> v1 * v2 end) 
|> Enum.filter(fn {k,_v} -> [m1, m2] |> Enum.all?(&Map.has_key?(&1, k)) end)
|> Map.new()
>%{b: 6}

Thoughts?

Most Liked

adamu

adamu

:maps.intersect(m1, m2)
%{b: 3}

:maps.intersect_with(fn _k , v1, v2 -> v1 * v2 end, m1, m2)
%{b: 6}
josevalim

josevalim

Creator of Elixir

Elixir main requires Erlang/OTP 24. Therefore if someone wants to submit a PR that adds intersect/2 and intersect/3, it will be welcome.

rvirding

rvirding

Creator of Erlang

There is only ONE type of map in the BEAM. The maps in Elixir are exactly the same maps as in Erlang. Seeing Erlang is the base language on the BEAM Elixir could not have had maps before the BEAM and Erlang implemented them.

iex(1)> m1 = %{a: 1, b: 1, c: 1}
%{a: 1, b: 1, c: 1}
iex(2)> m2 = %{a: 2 , c: 2, d: 2}
%{a: 2, c: 2, d: 2}
iex(3)> mi = :maps.intersect(m1, m2)
%{a: 2, c: 2}
iex(4)> :io.write(m1)       
#{a => 1,b => 1,c => 1}:ok
iex(5)> :io.write(m2)
#{a => 2,c => 2,d => 2}:ok
iex(6)> :io.write(m1)               
#{a => 1,b => 1,c => 1}:ok

The :io.write function is an output function in the Erlang io module and prints the maps which shows they are the same maps as in Erlang.

The :maps.intersect/2 function first came in OTP 24.0 so it may not be used yet in the Map module.

adamu

adamu

Just in case anybody has ideas:

Eiji

Eiji

All you have to do is a simple reducer. :smiling_imp:

defmodule Example do
  @spec sample(map(), map(), (Map.key(), Map.value(), Map.value() -> Map.value())) :: map()
  def sample(left, right, func) when is_map(left) and is_map(right) and is_function(func, 3) do
    Enum.reduce(left, %{}, fn
      {key, value}, acc when is_map_key(right, key) ->
        Map.put(acc, key, func.(key, value, right[key]))

      _pair, acc ->
        acc
    end)
  end
end

iex> Example.sample(%{a: 1, b: 2}, %{b: 3, c: 4}, fn _k, v1, v2 -> v1 * v2 end)
%{b: 6}

Helpful resources:

  1. Guides |> Typespecs @ Elixir documentation
  2. Enum.reduce/3
  3. Kernel.is_function/2
  4. Kernel.is_map/1
  5. Kernel.is_map_key/2
  6. Map.put/3

Where Next?

Popular in Discussions Top

hauleth
Maybe some of you know that there was (is?) something like BERT-RPC which in short is simplified version of External Term Format (also kn...
New
tristan
First announced on the Erlang Forum, BEAMup is a tool for installing a managing the active instance of BEAM languages. It has support for...
New
arcanemachine
Just wondering what the community currently thinks, prefers, and/or recommends for working with UI components. (e.g. daisyUI, MishkaChele...
New
thiagomajesk
I came across this PKGX tool the other day, if anyone here is using it, could you share your experience? I’m wondering how useful it wou...
New
James_E
I see that the current ExUnit source code has support for rich failure messages on a small whitelist of “recognized” assertion patterns, ...
New
fireproofsocks
I’m not a Lambda fan-boy because I think it’s overprescribed as a cure-all for every possible problem when in reality, Lambdas are best s...
New
wanton7
Our company has used virtual actor framework called Orleans that is for C#/.Net Framework. There are clones of it in Erlang GitHub - erle...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
bartblast
Some great comments in the home page thread shifted toward what you’d like to see in Hologram’s future, particularly standalone mode. I’v...
New
sergio
Laravel just announced their Series A round for $57 million. If Laravel wasn’t already the defacto PHP stack, it now most certainly is. T...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
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
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
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