axelson

axelson

Scenic Core Team

How can you assert that a map in a variable matches another map that is a superset?

Given these two maps:

map1 = %{a: 1}
map2 = %{a:1, b: 2}

This works fine:

%{a: 1} = map2

But these do not:

iex> ^map1 = map2
** (MatchError) no match of right hand side value: %{a: 1, b: 2}
iex> match?(^map1, map2)
false

Assuming I have a subset of what I want to match in a variable is there a way to use pattern matching to check that I have a subset?

Marked As Solved

peerreynders

peerreynders

The trivial/pedestrian (i.e. no pattern match) way:

map1 = %{a: 1}
map2 = %{a: 1, b: 2}

set1 = MapSet.new(map1)
set2 = MapSet.new(map2)

IO.puts("map1 ⊆ map2 #{MapSet.subset?(set1, set2)}")
IO.puts("map2 ⊆ map1 #{MapSet.subset?(set2, set1)}
$ elixir demo.exs
map1 ⊆ map2 true
map2 ⊆ map1 false
$ 

or

map1 = %{a: 1}
map2 = %{a: 1, b: 2}
map3 = %{c: 3}

subset? =
  fn (map1, map2) ->
    keys = Map.keys(map1)
    map2
    |> Map.take(keys)
    |> Map.equal?(map1)
  end

IO.puts("map1 ⊆ map2 #{subset?.(map1, map2)}")
IO.puts("map2 ⊆ map1 #{subset?.(map2, map1)}")
IO.puts("map3 ⊆ map2 #{subset?.(map3, map2)}")
$ elixir demo2.exs
map1 ⊆ map2 true
map2 ⊆ map1 false
map3 ⊆ map2 false

and another

map1 = %{a: 1}
map2 = %{a: 1, b: 2}
map3 = %{c: 3}

subset? =
  fn (map1, map2) ->
    in_other =
      fn {key, value} ->
        {:ok, value} == Map.fetch(map2, key)
      end
    map1
    |> Map.to_list()
    |> Enum.all?(in_other)
  end

IO.puts("map1 ⊆ map2 #{subset?.(map1, map2)}")
IO.puts("map2 ⊆ map1 #{subset?.(map2, map1)}")
IO.puts("map3 ⊆ map2 #{subset?.(map3, map2)}")
$ elixir demo3.exs
map1 ⊆ map2 true
map2 ⊆ map1 false
map3 ⊆ map2 false
$ 

I have the sneaking suspicion that the pattern is a compile time construct - it’s the binding that happens at runtime.

Also Liked

manukall

manukall

this doesn’t do what you would think, though:

iex(4)> match?(a, %{x: 5})
true
peerreynders

peerreynders

My gut pick is this one:

subset? =
  fn (map1, map2) ->
    in_other =
      fn {key, value} ->
        {:ok, value} == Map.fetch(map2, key)
      end
    map1
    |> Map.to_list()
    |> Enum.all?(in_other)
  end

as it simply verifies that all the necessary key/value pairs are present and will stop as soon as that is not the case.

In this case I also prefer to use fetch/2 in order the leverage the underlying map functionality rather than relying on in/2’s macro magic even if it makes the code a bit more verbose (so be it).

One thing to be aware of is that the empty set is a subset of any other set - the same is true for empty maps.

NobbZ

NobbZ

Do not pin here:

iex(1)> a = %{a: 1}
iex(2)> b = %{a: 1, b: 2}
iex(3)> match?(a, b)
true
kelvinst

kelvinst

Now I see my code is actually the same as @peerreynders second suggestion but in only one line.

If you want also, his last suggestion can be written as:

map1 = %{a: 1}
map2 = %{a: 1, b: 2}

map1
|> Map.to_list()
|> Enum.all?(&(&1 in map2))

But I still think MapSet.subset?/2 is clearer, and as you can see in its code, looks like it does pretty much the same thing.

kelvinst

kelvinst

Now that @axelson has a workaround for it, I want to bring a little discussion: shouldn’t his example work? I mean this one:

map1 = %{a: 1}
map2 = %{a: 1, b: 2}

^map1 = map2

I totally expected it to work. Didn’t you?​

I mean, if we think logically: if %{a: 1} = b works and
a = %{a: 1}, then ^a = b should work.

Do any of you know why it doesn’t? Is there a specific reason for it?

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
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
rms.mrcs
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....
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
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

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
rms.mrcs
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....
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement