Use a macro inside a function's definition


I have a function called f′ and I want to use a macro called @diff inside the function’s definition:

macro diff(expression)
    return :(2x)

f′(x) = @diff x^2


Yet once I run this code, this error message is shown:

ERROR: LoadError: UndefVarError: x not defined
 [1] f′(x::Int64)
   @ Main ~/Code/julia/script.jl:5
 [2] top-level scope
   @ ~/Code/julia/script.jl:7
in expression starting at /Users/jeroen/Code/julia/script.jl:7

And this is the code that the macro produces (using @macroexpand @diff x^2):

2 * Main.x

I think the problem is that Julia binds the variable x to the main scope, instead of the function scope.

How can I overcome this problem and use macros inside function definitions?

Thank you!

The macro definition is missing an esc call to indicate that you want to make the macro unhygienic and potentially corrupt the caller’s namespace:

macro diff(expression)

With that, the rest of your code works.

1 Like