Hi there,
I would like to learn a bit more about generated functions. My goal is to convert a struct into a tuple. I already achieved that if I want to convert all fields
struct Teststruct{A,B,C}
a :: A
b :: B
c :: C
end
@generated function to_tuple_generated(x)
tup = Expr(:tuple)
for i in 1:fieldcount(x)
push!(tup.args, :(getfield(x, $i)) )
end
return :($tup)
end
te = Teststruct(1., 2., 3)
to_tuple_generated(te) #(1.00, 2.00, 3)
Now, how would I proceed if I only want a specific subset of the fields, say .a and .c in the tuple? I get that the @generated function
only sees the input type, so I tried to make it working with :($argument )
, but did not succeed. My unsuccessful approach:
#idx are all keys/indices that should be returned as
@generated function to_tuple_generated(x, idx)
tup = Expr(:tuple)
for i in :($idx) #Here only Type{idx} is visible and function errors
push!(tup.args, :(getfield(x, $i)) )
end
return :($tup)
end
idx = [1, 3] #Create tuple from first and third field element
idx2 = (:a, :c) #Create tuple from first and third field element
to_tuple_generated(te, idx) #should be (1., 3)
to_tuple_generated(te, idx2) #should be (1., 3)