gpt4 book ai didi

julia - Julia 表达式中类似列表理解的扩展?

转载 作者:行者123 更新时间:2023-12-05 00:56:12 26 4
gpt4 key购买 nike

在 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_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)

关于julia - Julia 表达式中类似列表理解的扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36709393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com