Macros 从宏中的符号生成符号

Macros 从宏中的符号生成符号,macros,metaprogramming,julia,Macros,Metaprogramming,Julia,我不知道该如何表达。我有这样一个宏: macro dothing(xxxx) # create a new symbol ZC_xxxx = symbol("ZC_"*string(xxxx)) # esc so that variables are assigned in calling scope return esc(quote # assign something to the new symbol $ZC_xxxx = [555.0, 666.0, 7

我不知道该如何表达。我有这样一个宏:

macro dothing(xxxx)
  # create a new symbol
  ZC_xxxx = symbol("ZC_"*string(xxxx))

  # esc so that variables are assigned in calling scope
  return esc(quote
    # assign something to the new symbol
    $ZC_xxxx = [555.0, 666.0, 777.0]

    # Store in a the dataframe
    t[:(:($ZC_xxxx))] = $ZC_xxxx
  end)
end

t = DataFrame()
@dothing(ABCD)
我想让宏做两件事:在调用范围中创建一个新变量,称为ZC_ABCD;使用此名称和返回值的值向dataframe添加一个新列。i、 e.我希望宏返回的表达式如下所示:

ZC_ABCD = [555.0, 666.0, 777.0]
t[:ZC_ABCD] = ZC_ABCD
在上面的演示中,如果我在从宏返回之前添加对
show(expr)
的调用,它将显示以下内容:

ZC_ABCD = [555.0, 666.0, 777.0]
t[:ZC_xxxx] = ZC_ABCD
i、 e.请注意,数据帧中索引查找中使用的符号不正确


如何从宏中获得所需的结果?关于符号插值,我不了解什么?

在使用符号生成表达式之前,请尝试引用符号:

macro dothing(xxxx)
    # create a new symbol
    ZC_xxxx = symbol("ZC_"*string(xxxx))
    q = Expr(:quote, ZC_xxxx)

    # esc so that variables are assigned in calling scope
    return esc(quote
        # assign something to the new symbol
        $ZC_xxxx = [555.0, 666.0, 777.0]

        # Store in a the dataframe
        t[$q] = $ZC_xxxx
    end)
end

这就是说,从风格上来说,这种变量操作有点冒险,因为仅仅通过查看调用就很难猜出
@dothing
做了什么(它引用了
@dothing(ABCD)
表达式中没有出现的各种数量)。

很好,谢谢。我知道这有点冒险,但这是为了大量的代码生成,我认为这个宏比为许多不同的变量维护相同的代码要容易得多。这很有趣,但最终你是正确的。当我在表格中传递时,它作为一个函数,可读性更强,不那么脆弱