Nicu Stiurca
Nicu Stiurca

Reputation: 8697

list-comprehension-like expansion inside Julia expression?

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

For example, say I have some symbols and types, and 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 complicated expressions like this is both extremely error prone (because you have be intimately knowledgeable with the Expr data type in order to know, eg that the expressions for the data types of the tuple have to be stored in new_type.args[3].args) and also extremely brittle in that any change to the AST of the expression being built would mean having to change where/how every sub-expression is stored.

So is there a way to do something like

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

and end up with the same expression as above?

Upvotes: 4

Views: 273

Answers (1)

mbauman
mbauman

Reputation: 31372

Yes, you can splat arrays of expressions directly into 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)

Upvotes: 5

Related Questions