Is there an equivalent of is_string, is_number, is_integer, is_binary for the Elixir Decimal package?
If not, what are some of the ways to pattern match for a Decimal?
Decimal is an Elixir struct. So, you can match on it with %Decimal{}. This can be added to your function clause or in case statements. Here are couple examples:
def add(%Decimal{} = x, %Decimal{} = y), do: Decimal.add(x, y)
case num do
%Decimal{} = x -> # ...
num when is_integer(num) -> # ...
_ -> # default case
end
The same approach applies for matching any Elixir struct. The matching rules are similar to maps. However, a struct contains only the fields they are defined with and all those fields are present in the struct.
This means that you cannot matching on presence of a file must be done on the default value. For example:
# to match a struct that contains the `:mode` key you can do this:
def my_fun(%{mode: _}), do: # matches if the :mode key is present
def my_fun(%{}), do: # default case when map does not contain the :mode key
# to do the same with a struct
def MyStruct do
defstruct mode: nil, other: true
end
def my_fun(%MyStruct{mode: mode}) when not is_nil(mode), do: # do something with mode
def my_fun(%MyStruct{}), do: # default case when mode is nil
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