Erlang vs Elixir Macros -


i have came across erlang code trying convert elixir me learn both of languages , understand differences. macros , metaprogramming in general topic still trying head around, understand confusion.

the erlang code

-define(p2(mat, rep),          p2(w = mat ++ stm) -> m_rep(0, w, stm, rep))  % m_rep function defined. 

to me, seems in above code, there 2 separate definitions of p2 macro map private function called m_rep. in elixir though, seems possible have 1 pattern matching definition. possible have different ones in elixir too?

these not 2 definitions. first line macro, second line replacement. confusing bit macro has same name function generating clauses. example when using macro this:

?p2("a", "b"); ?p2("c", "d"). 

the above expanded to:

p2(w = "a" ++ stm) -> m_rep(0, w, stm, "b"); p2(w = "c" ++ stm) -> m_rep(0, w, stm, "d"). 

you can use erlc -p produce .p file show effects of macro expansion on code. check out simpler, compilable example:

-module(macro). -export([foo/1]).  -define(foo(x),         foo(x) -> x).  ?foo("bar"); ?foo("baz"); ?foo("qux"). 

using erlc -p macro.erl following output macro.p:

-file("macro.erl", 1).  -module(macro).  -export([foo/1]).  foo("bar") ->     "bar"; foo("baz") ->     "baz"; foo("qux") ->     "qux". 

in elixir can define multiple function clauses using macros well. more verbose, think clearer. elixir equivalent be:

defmodule mymacros   defmacro p2(mat, rep)     quote       def p2(w = unquote(mat) ++ stm)         m_rep(0, w, stm, unquote(rep))       end     end   end end 

which can use define multiple function clauses, erlang counterpart:

defmodule mymodule   require mymacros    mymacros.p2('a', 'b')   mymacros.p2('c', 'd') end 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -