How to code-gen unrolled loop over a tuple?

The metaprogramming solution is to use generated functions. This should do the trick:

@generated function pickfunc(data, funcs::NTuple{N}, cumweights::Tuple) where {N}
    ex = quote
        x = rand()
    end
    for i in 1:(N - 1)
        line = :(x < cumweights[$i] && (usefunc(data, funcs[$i]); return))
        push!(ex.args, line)
    end
    lastline = :(usefunc(data, funcs[$N]); return)
    push!(ex.args, lastline)
    return ex
end
1 Like