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)

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?


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):

1 Like