如何在Julia Expr中插入符号作为符号?

时间:2018-01-16 01:43:32

标签: julia metaprogramming

我想创建一个引号,它会在变量:abc中保存符号x并将其推送到数组a中。但是我只能得到变量abc。语法:$x似乎不正确(不是我想要的)。这样做的语法是什么?:

julia> x = :abc
julia> expr = quote
         a = []
         push!(a, $x)
         push!(a, :($x))
         push!(a, :$x)
         a
       end
quote  
    a = [] 
    push!(a, abc) 
    push!(a, $(Expr(:quote, :($(Expr(:$, :x))))))
    push!(a, :$ * x) 
    a
end

所需的输出是:

quote  
    a = [] 
    push!(a, :abc) 
    a
end

1 个答案:

答案 0 :(得分:5)

您需要使用相当于$(Meta.quot(:abc))的{​​{1}}添加另一层报价。

使用:

$(Expr(:quote, :abc))

设定:

              _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.2 (2017-12-13 18:08 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-pc-linux-gnu

推:

julia> x = :abc
:abc

julia> es = [x, :x, :(:x), Expr(:quote, x), Meta.quot(x)]    # :(x) is parsed as :x
5-element Array{Any,1}:                                  
 :abc                                                    
 :x                                                      
 :(:x)                                                   
 :(:abc)                                                 
 :(:abc)                                                 

julia> blk = Expr(:block)
quote
end

评估:

julia> push!(blk.args, :(a = []))
1-element Array{Any,1}:
 :(a = [])

julia> blk
quote
    a = []
end

julia> for e in es
           push!(blk.args, :(push!(a, $e)))
       end

julia> blk
quote
    a = []
    push!(a, abc)
    push!(a, x)
    push!(a, :x)
    push!(a, :abc)
    push!(a, :abc)
end

julia> push!(blk.args, :a)
7-element Array{Any,1}:
 :(a = [])
 :(push!(a, abc))
 :(push!(a, x))
 :(push!(a, :x))
 :(push!(a, :abc))
 :(push!(a, :abc))
 :a

修正:

julia> blk
quote
    a = []
    push!(a, abc)
    push!(a, x)
    push!(a, :x)
    push!(a, :abc)
    push!(a, :abc)
    a
end

julia> eval(ans)
ERROR: UndefVarError: abc not defined
Stacktrace:
 [1] eval(::Module, ::Any) at ./boot.jl:235
 [2] eval(::Any) at ./boot.jl:234

最后:

julia> deleteat!(blk.args, 2)
6-element Array{Any,1}:
 :(a = [])
 :(push!(a, x))
 :(push!(a, :x))
 :(push!(a, :abc))
 :(push!(a, :abc))
 :a

julia> blk
quote
    a = []
    push!(a, x)
    push!(a, :x)
    push!(a, :abc)
    push!(a, :abc)
    a
end

julia> eval(ans)
4-element Array{Any,1}:
 :abc
 :x
 :abc
 :abc