Macros and keyword list parameters

I am studying how macros are defined/called with keyword parameters.

Looking first at if – I thought that “maybe” do and else were “just regular keywords.”
Then I thought: Maybe do is special and else is not?
Now I think maybe they’re both special?

I made an if2 which works fine:

  defmacro if2(condition, do: do_block, else: else_block) do
    quote do
      case unquote(condition) do
        x when x in [false, nil] -> unquote(else_block)
        _                        -> unquote(do_block)
      end
    end
  end

But… if i change the definition (and the call) from else to otherwise, it doesn’t work.

Can someone explain? Is the parser treating this macro specially somehow?

Hal

Yes I believe do, else, catch, rescue and after are special words for the parser.

Calling like this should work: if2(is_true(thing), do: accept(), otherwise: do_something_else()), but it is not what you want I guess.

1 Like

As already pointed out, else, catch, rescue, and after are special. Here’s where that happens:

Thanks very much for these replies.

Here’s a related doc link (that was posted in slack):

https://hexdocs.pm/elixir/syntax-reference.html#do-end-blocks

1 Like