Your Elixir Tips Thread

My fave is __CALLER__ struct has a context key which might be used to distingush context of macro invocation (might be :guard when invoked in guards, :match when invoked in matches, or nil otherwise.) Here is the self-explanatory example from Kernel.or/2 macro

  defmacro left or right do
    case __CALLER__.context do
      nil -> build_boolean_check(:or, left, true, right)
      :match -> invalid_match!(:or)
      :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right)))
    end
  end

It helped me to build the MapSet matchers fwiw.

2 Likes