【问题标题】:Produce a symbol from a symbol in a macro从宏中的符号生成符号
【发布时间】:2015-02-27 09:00:18
【问题描述】:

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

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;使用此名称和返回值的值向数据框添加一个新列。即我希望从宏返回的表达式如下所示:

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

即请注意,在数据框中的索引查找中使用的符号不正确。

如何从宏中获得所需的结果?我对符号插值有什么不了解的地方?

【问题讨论】:

    标签: macros metaprogramming julia


    【解决方案1】:

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

    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) 中没有出现的各种数量表达式)。

    【讨论】:

    • 完美,谢谢。我知道这有点冒险,但它适用于大量代码生成,我认为这个宏比为许多不同的变量维护相同的代码更容易。
    • 这很有趣,但最终你是对的。作为我在表格等中传递的函数,它更具可读性且不那么脆弱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2021-07-13
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多