我有点厌倦了为输入类型的不同排列定义函数,例如
f(x::MyType1, y::MyType2) = x.data + y.data
f(y::MyType2, x::MyType1) = x.data + y.data
所以决定尝试一个返回上述两个定义的宏。
我能够制作一个宏来切换参数输入,但我无法让它返回多个函数定义。
所以这有效:
julia> macro argrev(ex)
if (ex.head == :(=)) && (ex.args[1].head == :call)
ex_ = copy(ex)
args = ex_.args[1].args
args[2:3] = args[[3, 2]]
return ex_
end
return ex
end
@argrev (macro with 1 method)
julia> @argrev f(x::Int, y::Float64) = x + y
f (generic function with 1 method)
julia> f(2, 3.5)
MethodError: no method matching f(::Int64, ::Float64)
julia> f(3.5, 2)
5.5
不过,我不知道如何返回 ex
和 ex_
。这是我的尝试之一:
julia> macro argrev1(ex)
if (ex.head == :(=)) && (ex.args[1].head == :call)
ex_ = copy(ex)
args = ex_.args[1].args
args[2:3] = args[[3, 2]]
return quote
ex
ex_
end
else
return ex
end
end
@argrev1 (macro with 1 method)
julia> @argrev1 f(x::Int, y::Float64) = x + y
UndefVarError: ex_ not defined
此错误是怎么回事,如何返回两个表达式,或以其他方式实现我在这里尝试做的事情?
编辑:看起来像this是相关的,但我不太明白应该如何使其适应我的情况。
最佳答案
在 quote
block 中,您需要像这样插入 ex
和 ex_
return quote
$ex
$ex_
end
关于macros - 具有多个返回表达式的 Julia 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385408/