Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a collection of symbols

I'm trying to escape a collection of symbols so that way I get a collection of the variables, but am running into issues. Here's an MWE:

macro escape_all(x...)
    :($(esc.(x))...)
end
x = 1
y = 2
z = 3
macroexpand(:(@escape_all x y z))

This returns

:(((:($(Expr(:escape, :x))), :($(Expr(:escape, :y))), :($(Expr(:escape, :z))))...,))

but what I'm looking for it to return is just

(x,y,z)
like image 264
Chris Rackauckas Avatar asked Oct 17 '22 21:10

Chris Rackauckas


1 Answers

Calling Expr explicitely works:

julia> macro escape_all(xs...)
           Expr(:tuple, esc.(xs)...)
       end
@escape_all (macro with 1 method)

julia> @macroexpand @escape_all x y z
:((x, y, z))

But you can also use the following unquote syntax in a context where list-splicing (like ,@ in Lisp, I guess) makes sense:

julia> macro escape_list(xs...)
           :([$(esc.(xs)...)])
       end
@escape_list (macro with 1 method)

julia> macro escape_f(xs...)
           :(f($(esc.(xs)...)))
       end
@escape_f (macro with 1 method)

julia> @macroexpand @escape_list x y z
:([x, y, z])

julia> @macroexpand @escape_f x y z
:((Main.f)(x, y, z))

Funnily, I never saw $(x...) to be talked about anywhere. I stumbled upon it recently reading someone's code. But it's mentioned in the current "latest" docs as splatting interpolation.

like image 80
phipsgabler Avatar answered Oct 20 '22 23:10

phipsgabler