Why can't I generate a function with multiple arguments using Symbol("arg1,arg2")?

I’m not sure what’s going on here, and I’m not sure if this is a valid use of Symbols either.

julia> for TA in [Symbol("a,b")]
       @eval f($TA) = a + b
       end

julia> methods(f)
# 1 method for generic function "f":
[1] f(a,b) in Main at REPL[1]:2

julia> f(1,2)
ERROR: MethodError: no method matching f(::Int64, ::Int64)
Closest candidates are:
  f(::Any) at REPL[1]:2
Stacktrace:
 [1] top-level scope at REPL[3]:1

julia> f(1)
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] f(::Int64) at ./REPL[1]:2
 [2] top-level scope at REPL[4]:1

What exactly is being generated here?

Macro interpolation doesn’t work the same as string interpolation. I.e. this is not what you’re getting in that eval

julia> TA = Symbol("a,b");

julia> "f($TA)"
"f(a,b)"  # you're not getting this. At least not the way you think...

You’re getting something more like

f(Symbol("a, b")) = a + b

So it’s a one argument function, with input argument Symbol("a, b"). What’s incredibly bizarre about that input argument name, is that it prints as though a and b are different things! That’s what’s throwing you off:

julia> methods(f)
# 1 method for generic function "f":
[1] f(a,b) in Main at REPL[5]:1

julia> f(1,1)
ERROR: MethodError: no method matching f(::Int64, ::Int64)
Closest candidates are:
  f(::Any) at REPL[5]:1
#...
julia> f(1)
ERROR: UndefVarError: a not defined
#...

Note that in the first case, there is no such function at all. The method printout is just messed up because your symbol is really strange. In the second case, there is such a function (one argument) but it doesn’t know what to do with a and b, since they are not the inputs.

2 Likes

You probably want something like this instead:

julia> for TA in [[:a, :b]]
           @eval f($(TA...)) = a + b
       end
4 Likes

Thanks, this was quite insightful!

This also seems to be a printing bug, Symbol("a,b") in method signatures should be displayed as var"a,b". Would you mind opening an issue?

3 Likes

Filed an issue

6 Likes