Use a macro inside a function's definition

Hello,

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)
end

f′(x) = @diff x^2

print(f′(10))

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

ERROR: LoadError: UndefVarError: x not defined
Stacktrace:
 [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)
   esc(:(2x))
end

With that, the rest of your code works.

2 Likes

@johnmyleswhite thank you, this was stumping me.