Interpolate array elements into `Base.Cartesian.@nif`

metaprogramming

#1

This is a continuation of my question in Function that creates generated function using interpolation?

However, since the original question in that topic is now solved, I have restated my new question in a simplifed and easier to understand form:

My goal is to produce an if-then quote block based on the array elements of lex:

julia> lex = [:(x^2),:(2x),2];

julia> macroexpand(quote
           Base.Cartesian.@nif($(length(lex)),
               i->(p == i-1),
               i->($(:(lex[i]))))
       end)
quote  # REPL[224], line 2:
    if p == 0
        lex[1]
    else 
        if p == 1
            lex[2]
        else 
            lex[3]
        end
    end
end

However, the code I want to end up with should look like this:

quote  # REPL[224], line 2:
    if p == 0
        x^2
    else 
        if p == 1
            2x
        else 
            2
        end
    end
end

Is it possible to do this using Base.Cartesian.@nif or do I need to create my own function that generates the if-then block structure? The main problem is that it does not seem to be possible to reference both i and lex at the same time in the same scope.

Please let me know if someone knows or figures out how to do it! Regards,


#2

I don’t think the nif macro supports this. It does evaluation of some “pure” expressions (e.g. basic arithmetic) but it cannot know that you want to evaluate the getindex function calls at macro expansion time and not runtime.