【问题标题】:Escaping a collection of symbols转义符号集合
【发布时间】:2018-08-26 12:48:28
【问题描述】:

我正在尝试转义符号集合,以便获得变量集合,但遇到了问题。这是一个 MWE:

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

返回

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

但我希望它返回的只是

(x,y,z)

【问题讨论】:

    标签: julia metaprogramming


    【解决方案1】:

    调用Expr 明确有效:

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

    但您也可以在列表拼接(我猜想像 Lisp 中的 ,@)有意义的上下文中使用以下取消引用语法:

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

    有趣的是,我从来没有见过 $(x...) 在任何地方被谈论。我最近在阅读某人的代码时偶然发现了它。但它在当前的“最新”文档中被称为splatting interpolation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2021-08-08
      • 1970-01-01
      • 2016-03-16
      • 2015-12-11
      相关资源
      最近更新 更多