Pregunta

In Erlang, we can define a macro like -define(TIME, 60 * 60). And from the invocation of macros such as ?TIME we can know exactly that they are macros.

In Elixir, however, the invocation of macros look like a function call. We can't distinguish macro invocations from function calls easily.

So, is there a way that we can name some of the macros which like a constant?

¿Fue útil?

Solución

In Erlang, a macro works as a template. So -define(TIME, 60 * 60) would effectively introduce 60 * 60 into your source code (which may be pre-calculated by the compiler in this specific case).

The equivalent in Elixir would be:

defmacro time do
 quote do
   60 * 60
 end
end

But this has exactly the same issues as the Erlang one. If you actually want to compute something expensive, it will still be calculated at runtime in all places you used the macro time.

That said, Elixir has another construct that allows you to pre-calculate a value, at compilation time, and simply re-use in your functions, which is via attributes:

defmodule MyModule do
  @time 60 * 60

  def using_time do
    @time
  end
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top