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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With