Hello,
I’m having some hard time trying to figure out how macros are working…
Let’s say I have some code where a certain variable is already defined (eg. x
) and where I’m using this variable within an expression that I have several times:
...
x = "Result:"
...
x <> a_function_outputting("a string")
...
x <> another_function_outputting("a string")
...
For convenience I wanted to define a function that will encapsulate this calling.
This concatenation is an example, of course.
Now since I never know what are the functions I can call alongside the repeating x <>
I wanted to define a macro that will expand appropriately to the above starting from some code like this:
print_x(a_function_outputting("a string"))
print_x(another_function_outputting("a string"))
When I do the following:
defmacro print_x(function) do
x <> function
end
I got the error that x is not defined here.
I tried many combination with quote
ing, unquote
ing and even Macro.escape
ing.
But I wasn’t able to achieve what I want.
In fact what I want is to get the literals like how #define
works in C.
NB: In order to avoid XY problem.
I want to achieve this kind of macro in Phoenix views where the function are helpers functions and where the variable is an assign (so it will even be @x
rather than x)
Thank you very much for any details.