Working with the end keyword in macros for array indices

Suppose I have a composite type array like this:

type myType
a::Int
b::Float
end

myArray=myType[]

      

For obvious reasons, I would like to be able to use simple indexing to access fields of composite types like this:

aVals=myArray[1:3].a

      

The following macro can successfully do this type of indexing if I have a numeric value iterated over the array:

macro getArray(exp)        
iter=eval(exp.args[1].args[2])
exp.args[1].args[2]=:i;
:[$(esc(exp)) for $(esc(:i)) in $iter]
end

      

How do I write a similar macro that is also capable of handling keyword array indices end

, i.e.

aVals=@getArray myArray[1:end].a

      

+3


source to share


1 answer


The following macro not only solves the indexing problem, but also sets the correct output type:



macro getArray(exp)
    quote
        ftype=typeof($(esc(exp.args[1]))[1].($(esc(exp.args[2]))));
        ftype[item.($(exp.args[2])) for item in $(esc(exp.args[1]))]
    end
end

      

+2


source







All Articles