How to check structure field type in Elixir?

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 possible to check if there is o.operator logic , arithmetic or nil ?

+8
elixir typechecking
source share
1 answer

Specix in Elixir - annotations, you cannot 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 
+8
source share

All Articles