axelson

axelson

Scenic Core Team

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?

Showing Posts 1 to 10

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.

NobbZ

NobbZ

Do not pin here:

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

manukall

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

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

NobbZ

Oh… Yeah, true, thats not what I had expected…

peerreynders

peerreynders

match?(a, %{x: 5})

That simply results in %{x: 5} being bound to a - i.e. it is a match that always succeeds, while a is subsequently never used (macro code from Kernel.match?/2).

Similar to:

a = %{a: 1}

match1 =
  case %{x: 5} do
    a -> true   # i.e. "%{x: 5}" is bound to "a" - a subsequently unused name
    _ -> false
  end

# Semantically similar to above case using a plain match/bind.
match2 =
  try do
    a = %{x: 5} # i.e. "%{x: 5}" is bound to "a" - a subsequently unused name
    true

  catch
    :error, {:badmatch, _} ->
      false

#  # --- rescue is PREFERRED in Elixir
#  rescue
#    _ in MatchError ->
#      false
  end

# https://elixir-lang.org/getting-started/try-catch-and-rescue.html#errors
#
# In Elixir, we avoid using try/rescue because WE DON’T USE ERRORS FOR CONTROL FLOW.

IO.puts("match?(a,{x: 5}) #{match1}")
IO.puts("alt_match?(a,{x: 5}) #{match2}")
$ elixir demo4.exs
warning: variable "a" is unused
  demo4.exs:1

warning: variable "a" is unused
  demo4.exs:5

warning: variable "a" is unused
  demo4.exs:12

match?(a,{x: 5}) true
alt_match?(a,{x: 5}) true
$
manukall

manukall

that’t my point :wink:

kelvinst

kelvinst

I would go with @peerreynders suggestion using MapSet. Or maybe:

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

Map.take(map2, Map.keys(map1)) == map1

But I guess any of @peerreynders suggestions have better performance, memory consumption and are clearer. So no reason to use mine. :wink:

axelson

axelson OP

Scenic Core Team

Thanks! It looks like using MapSet.subset?/2 is my best option

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? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews