我正在尝试编写一个宏来为类型层次结构定义多个方法。我的目标是以任意顺序枚举类型层次结构,通过为类型树中的每个结构定义一个order()
方法。
macro enum_type(type)
let type = eval(type)
next = [type]
methods = []
counter = 0
while(!isempty(next))
let current_type = pop!(next)
children = subtypes(current_type)
map(t -> push!(next, t), children)
push!(methods, :(order(::$current_type) = $(counter += 1)))
end
end
quote
$(methods...)
end
end
end
返回的表达式似乎不是在顶层中被评估的。有没有一种方法可以返回多个顶层表达式?
期望的行为是为层次结构中的每种类型创建一个方法,例如,请考虑:
@macroexpand @enum_type (AbstractFloat)
应编写一个名为
order(...)
的方法,从AbstractFloat开始将任意数量与类型树中的每个类型相关联。目前,带有AbstractFloat参数的宏扩展为:quote
#= none:14 =#
var"#57#order"(::AbstractFloat) = begin
#= none:10 =#
1
end
var"#57#order"(::Float64) = begin
#= none:10 =#
2
end
var"#57#order"(::Float32) = begin
#= none:10 =#
3
end
var"#57#order"(::Float16) = begin
#= none:10 =#
4
end
var"#57#order"(::BigFloat) = begin
#= none:10 =#
5
end
end
但是没有任何方法声明被评估。
@enum
宏会遮蔽来自 Base 的@enum
宏。 - Cameron Bieganek