Discussion:
[julia-users] What is the correct way for function parameter list generation with @eval?
Diego Javier Zea
2015-07-31 18:46:11 UTC
Permalink
Hi! I don't know how to generate parameter list of functions in order to
avoid a lot repetitive code:

julia> for (param, special) in [ (:(),:()), (:(, y),:(+ y)) ]
@eval begin
function f(x $(param), z)
x $(special) + z
end
end
end


f(1,2)
f(1,2,3)
ERROR: syntax: unexpected ,


julia> for (param, special) in [ (:(),:()), (:(y, ),:(y +)) ]
@eval begin
function f(x, $(param) z)
x + $(special) z
end
end
end


f(1,2)
f(1,2,3)
ERROR: syntax: unexpected )


julia> for (param, special) in [ (:(),:()), (:(y:(,) ),:(y :(+))) ]
@eval begin
function f(x, $(param) z)
x + $(special) z
end
end
end


f(1,2)
f(1,2,3)
ERROR: syntax: unexpected ,

Best,
Yichao Yu
2015-07-31 18:53:03 UTC
Permalink
Post by Diego Javier Zea
Hi! I don't know how to generate parameter list of functions in order to
julia> for (param, special) in [ (:(),:()), (:(, y),:(+ y)) ]
@eval begin
function f(x $(param), z)
x $(special) + z
end
end
end
Note that julia meta programming works on the AST level and not the
string level. Also note that operators are nothing other than a fancy
way to call a function.

julia> a = [:x, :y, :z]
3-element Array{Symbol,1}:
:x
:y
:z

julia> :(+($(a...)))
:(x + y + z)

julia> for p in [(), (:y,)]
@eval function f(x, $(p...), z)
+(x, $(p...), z)
end
end

julia> f(1, 2)
3

julia> f(1, 2, 3)
6

Depending on what you are doing, you might be better off using varadic
Post by Diego Javier Zea
f(1,2)
f(1,2,3)
ERROR: syntax: unexpected ,
julia> for (param, special) in [ (:(),:()), (:(y, ),:(y +)) ]
@eval begin
function f(x, $(param) z)
x + $(special) z
end
end
end
f(1,2)
f(1,2,3)
ERROR: syntax: unexpected )
julia> for (param, special) in [ (:(),:()), (:(y:(,) ),:(y :(+))) ]
@eval begin
function f(x, $(param) z)
x + $(special) z
end
end
end
f(1,2)
f(1,2,3)
ERROR: syntax: unexpected ,
Best,
Loading...