Defining own `else`

Hi

I know that I can create something like that

defmodule Test do
  defmacro wrap(do: do_expr, else: else_expr) do
    quote do
      IO.inspect unquote(do_expr)
      IO.puts "ELSE"
      IO.inspect unquote(else_expr)
    end
  end

and use it like

Test.wrap do
  :abc
else
  :bcd
end

and see

:abc
ELSE
:bcd

in stdout.
Also I can use after, rescue and other reserved words (macro?) instead of else.
Is it possible to define my own word (macro?) that will work same?

No.
</>

It’s not possible to define your own. The ones that are available are: do, else, after, rescue, and catch.

2 Likes

Thank you.
I found what I can do like that

defmacro wrap(do: do_expr, myown: else_expr) do
quote do
    unquote(do_expr)
    IO.puts "ELSE"
    unquote(else_expr)
  end
end

and use like

Test.wrap do: (IO.puts :abc), myown: (IO.puts :bcd)

and it will be working ok. It demonstrates that possible even pass block of code as method parameter. But it would be good if the developer could declare own keywords.

Is it planned to add possibility to declare custom keywords in Elixir?

No, this is not planned.

Thanks for all replies

I think that it will be very useful to allow creating custom keywords (or other name, but with behavior described above)

But for now topic is closed. Thank you

For note, a block can be defined multiple times, so:

myMacroCal do
  1
else
  2
else
  3
after
  4
end

Or whatever else is all valid and you can handle it in your macro (I’ve done it). You can also use something like -> (which binds very tightly) to do conditionals or whatever you want on the left and whatever else on the right, useful to split up a body like:

myMacroCal do
  1
else
  doSomething() -> doSomethingElse()
  42 -> 6.28
after
  4
end