Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match an empty MapSet

Tags:

elixir

Given a MapSet, how can one detect if it's empty using pattern matching?

# What goes in the question marks?
def my_func(????), do: IO.puts("This mapset is empty")
def my_func(%MapSet{}), do: IO.puts("This mapset is not empty")

my_func(MapSet.new())

If this were a list, I would have just matched it on ([]) but that doesn't work for MapSets (because the type is different)

Here are some of the other things I've tried, unsuccessfully.

def myfunc([]), do: IO.puts("This only works for lists")
# This is a syntax error
# def myfunc(MapSize.new())

def myfunc(%MapSet{}), do: IO.puts("This matches every mapset")
def myfunc(a) when map_size(a), do: IO.puts("the map size is always 3")
like image 661
AnilRedshift Avatar asked Dec 10 '22 07:12

AnilRedshift


1 Answers

A MapSet stores its entries in a field called map. I'm not 100% sure whether this is an implementation detail or is it guaranteed to remain the same, but for now you can check whether the map field is empty using map_size/1:

defmodule A do
  def empty?(%MapSet{map: map}) when map_size(map) == 0, do: true
  def empty?(%MapSet{}), do: false
end

IO.inspect A.empty?(MapSet.new)
IO.inspect A.empty?(MapSet.new([1, 2]))

Output:

true
false
like image 72
Dogbert Avatar answered Dec 12 '22 20:12

Dogbert