How to use a variable of `Symbol` type as a argument when using @eval to define function?

I try to use @eval to generate a function, with a Symbol as its argument, the following code works good:

arg = :(a::String)

@eval function hello($arg) print($arg) end

got a function signature as

hello(a::String)  ...

Then i modified the code as below:

arg  =  Symbol(:a,:(=),1)

@eval function hello($arg) print($arg) end

But i got this weird signature :

hello(var"a=1") ...

the signature that i expect should be :

hello(a=1) ...

can someone help me find the cause?

You are creating not a symbol but an expression, a=1. So, use an appropriate expression type:

julia> e = :(a=1)
:(a = 1)

julia> dump(e)
Expr
  head: Symbol =
  args: Array{Any}((2,))
    1: Symbol a
    2: Int64 1

julia> e = Expr(:(=), :a, 1)
:(a = 1)
1 Like

Note in general that a good way to figure out how to construct expressions for metaprogramming is to use dump on a quoted expression :(...), e.g.:

julia> dump(:(function hello(a=1); println(a); end))
Expr
  head: Symbol function
  args: Array{Any}((2,))
    1: Expr
      head: Symbol call
      args: Array{Any}((2,))
        1: Symbol hello
        2: Expr
          head: Symbol kw
          args: Array{Any}((2,))
            1: Symbol a
            2: Int64 1
    2: Expr
      head: Symbol block
      args: Array{Any}((3,))
        1: LineNumberNode
          line: Int64 1
          file: Symbol REPL[16]
        2: LineNumberNode
          line: Int64 1
          file: Symbol REPL[16]
        3: Expr
          head: Symbol call
          args: Array{Any}((2,))
            1: Symbol println
            2: Symbol a

Note, in particular, that arguments with default values are not = nodes in the abstract syntax tree (AST), and instead they are special kw nodes.

1 Like

it is a symbol, not an expression

arg  =  Symbol(:a,:(=),1)

> Symbol("a=1")

Symbol("a=1")

Got it ! thanks, you make my day! :grinning: