我正在尝试编写一个为类型层次结构定义多种方法的宏。我试图实现的是一种任意枚举类型层次结构的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
Run Code Online (Sandbox Code Playgroud)
返回的表达式似乎不在顶层计算。有没有办法返回多个顶级表达式?
所需的行为是为层次结构中的每种类型创建一个方法,例如,考虑
@macroexpand @enum_type (AbstractFloat)
Run Code Online (Sandbox Code Playgroud)
应该编写一个方法,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
#= …Run Code Online (Sandbox Code Playgroud) 假设我有一个向量
v = Any[1,2,3,4]
我想以这样的方式重新计算它的 eltype
typeof(v) = Vector{Int}
是否可以在无需手动连接 中的每个元素的情况下完成此操作v?