Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check type of struct's field 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 to possible to check whether o.operator is logic, arithmetic or nil ?

like image 623
zie1ony Avatar asked Jan 17 '15 18:01

zie1ony


1 Answers

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
like image 55
José Valim Avatar answered Sep 19 '22 10:09

José Valim