Evaluate Function Inside Quote

metaprogramming

#1

Hi! I’ve got a seemingly trivial problem to tackle…

Why does this work:

julia> function foo(x)
    f = quote
        function bar()
            a = $x
            println(a)
        end
    end
    eval(f)
end
foo (generic function with 1 method)

julia> foo(3)
bar (generic function with 1 method)

julia> bar()
3

And this doesn’t?

julia> baz(x) = $x
baz (generic function with 1 method)

julia> function foo2(x)
           f = quote
               function bar()
                   a = baz(x)
                   println(a)
               end
           end
           eval(f)
       end
foo2 (generic function with 1 method)

julia> foo2(1)
bar (generic function with 1 method)

julia> bar()
ERROR: error compiling bar: syntax: prefix "$" in non-quoted expression

Is there any way to get the behaviour of the first example with calling a function inside the quote?


#2

When building an expression, $(a) is used to splice the current value of a into that expression. The syntax $(a) cannot be used outside the expression (outside in the lexical sense).

The second example would be written as:

julia> baz(x) = x
baz (generic function with 1 method)

julia> function foo2(x)
           f = quote
               function bar()
                   a = $(baz(x))
                   println(a)
               end
           end
           eval(f)
       end

julia> foo2(1)
bar (generic function with 1 method)

julia> bar()
1

Here we splice the value of evaluating baz(x) into the expression.


#3

That works perfectly. Thanks!