Iterating over types of tuple elements in @generated function

I am writing a generated function and want to iterate over the types of the inputs to generate some splendid code. This works

@generated function foo(t...)
    for c ∈ t 
        Core.println(c)
    end
    return :( Core.println("foo !") )
end
foo(3.,1)

Float64
Int64
foo !

But for reasons I will not go into, I would like the inputs to be provided packed in a tuple. The following code does not work:

@generated function bar(t::Tuple)
    for c ∈ t   # !!! The type "Tuple{This,That}" is not iterable
        Core.println(c)
    end
    return :( Core.println("bar !") )
end
bar((3.,1))

MethodError: no method matching iterate(::Type{Tuple{Float64,Int64}})

The error message says it all: in the body of bar, t is the type Tuple{Float64,Int64} and one cannot iterate that. Makes sense. But can I obtain an iterator that generates Float64 and Int64?

I have a workaround, that works because I will only have one tuple in my real problem.

@generated function bar(t::Tuple)
    return :( foo(t...) )
end

Any better ideas?

Use the fieldtypes function:

fieldtypes(Tuple{Float64, Int}) === (Float64, Int) # true

@generated function bar(t::Tuple)
    for c ∈ fieldtypes(t)
        Core.println(c)
    end
    return :( Core.println("bar !") )
end
bar((3.,1))
3 Likes

Everything works!!! :grinning: and I get wiser.

Thanks Lucas!

1 Like