Similar to expanding the list in Julia's expression?

Is it possible to have something like a list comprehension for building complex expressions in Julia?

For example, let's say I have some characters and types, and you want to build a type from them. Right now, I have to do something like.

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)] 

This works in that new_type is an expression containing

 :(type Foo a::Int64 b::Float32 c::Char end) 

But building complex expressions like this is extremely error-prone (because you know that with the Expr data Expr you should know well, for example, that expressions for tuple data types should be stored in new_type.args[3].args ), and also extremely fragile, since any change in AST for a constructed expression means a change in where / how each subexpression is stored.

So there is a way to do something like

 :(type Foo $(sym::typ for (sym,typ) in zip(syms,typs)) end) 

and end with the same expression as above?

+5
source share
1 answer

Yes, you can plan arrays of expressions directly in the syntax:

 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) 
+5
source

Source: https://habr.com/ru/post/1247402/


All Articles