Let's say I have:
defmodule Operator do
defstruct operator: nil
@type t :: %Operator {
operator: oper
}
@type oper :: logic | arithmetic | nil
@type logic :: :or | :and
@type arithmetic :: :add | :mul
end
then I can:
o = %Operator{operator: :and}
Is it to possible to check whether o.operator
is logic
, arithmetic
or nil
?
Typespecs in Elixir are annotations, you can't really interact with them from your code without repeating part of them. Therefore, you can write:
def operator(%Operator{operator: op}) when op in [:or, :and, :add, :mul, nil] do
...
end
Or alternatively:
@ops [:or, :and, :add, :mul, nil]
def operator(%Operator{operator: op}) when op in @ops do
...
end
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