Elixir macros: how to define function with dynamic arity -


refer post: how create dynamic function name using elixir macro?.

the post above asked how use macro generate function without arguments, wonder how generate functions arguments ?

assume there macro warp, write code like:

warp fun, [args], :ok 

and generate code like:

fun(args), do: :ok 

if want generate dynamic list of arguments, need use unquote_splicing this:

defmacro warp(name, argument_names, code)   quote     def unquote(name)(unquote_splicing(argument_names))       unquote(code)     end   end end 

then later

warp :foo, [a, b], {:ok, a, b} 

which generates

def foo(a, b), do: {:ok, a, b} 

if call produce

foo(1, 2) # {:ok, 1, 2} 

you can define macro without unquote_splicing , pass down combined name , arguments def:

defmacro warp(name_and_args, do: code)   quote     def unquote(name_and_args)       unquote(code)     end   end end 

this means need invoke warp invoke def, example:

warp foo(a, b), do: {:ok, a, b} 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -