Ruby has open classes that are very convenient (albeit offended by some), and Elixir borrows Ruby a lot, so I expected Elixir to let me open the module again and add macros to it after closing it, but this doesnβt work like I tried . Is there any way to do this? Is this feature still available in Elixir?
To make this concrete, let's take an example from Chris McCord. Elixir metaprogramming:
defmodule Math do defmacro say({:+, _, [lhs, rhs]}) do quote do lhs = unquote(lhs) rhs = unquote(rhs) result = lhs + rhs IO.puts "#{lhs} plus #{rhs} is #{result}" result end end defmacro say({:*, _, [lhs, rhs]}) do quote do lhs = unquote(lhs) rhs = unquote(rhs) result = lhs * rhs IO.puts "#{lhs} times #{rhs} is #{result}" result end end end
If I then add a macro to subtract
defmodule Math do defmacro say({:-, _, [lhs, rhs]}) do quote do lhs = unquote(lhs) rhs = unquote(rhs) result = lhs - rhs IO.puts "#{lhs} minus #{rhs} is #{result}" result end end end
I get a warning that I am overriding the Math module and the initially defined macros fail. Thus, it is obvious that my approach is not right, but is there another approach that can achieve the same goal?
elixir
iconoclast
source share