Julia表达式中的列表式扩展?
在Julia中构建复杂表达式时,是否可能有类似列表理解的功能 例如,假设我有一些符号和类型,并希望从中构建一个类型。现在,我必须做一些类似的事情Julia表达式中的列表式扩展?,julia,Julia,在Julia中构建复杂表达式时,是否可能有类似列表理解的功能 例如,假设我有一些符号和类型,并希望从中构建一个类型。现在,我必须做一些类似的事情 syms = [:a, :b, :c] typs = [Int, Float32, Char] new_type = :(type Foo end) new_type.args[3].args = [:($sym::$typ) for (sym,typ) in zip(syms,typs)] 这是因为new\u type是一个包含 :(type Fo
syms = [:a, :b, :c]
typs = [Int, Float32, Char]
new_type = :(type Foo end)
new_type.args[3].args = [:($sym::$typ) for (sym,typ) in zip(syms,typs)]
这是因为new\u type
是一个包含
:(type Foo
a::Int64
b::Float32
c::Char
end)
但是像这样构建复杂的表达式非常容易出错(因为您必须熟悉Expr
数据类型才能知道,例如元组数据类型的表达式必须存储在new_type.args[3].args
)而且非常脆弱,因为对正在构建的表达式的AST的任何更改都意味着必须更改每个子表达式的存储位置/方式
那么有没有一种方法可以像
:(type Foo
$(sym::typ for (sym,typ) in zip(syms,typs))
end)
并以与上面相同的表达式结束?是的,您可以将表达式数组直接转换为语法:
julia> :(type Foo
$([:($sym::$typ) for (sym,typ) in zip(syms,typs)]...)
end)
:(type Foo # none, line 2:
a::Int64
b::Float32
c::Char
end)
谢谢,我想我的思路是对的,只是语法不正确。