Dealing with end keyword in macros for array indices

81 views Asked by At

Suppose I have an array of a composite type as follows:

type myType
a::Int
b::Float
end

myArray=myType[]

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

aVals=myArray[1:3].a

The following macro can successfully accomplish this type of indexing, as long as I have a numeric iterable for 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 can I write a similar macro that is also capable of dealing with array indices with the end keyword, i.e.:

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

There are 1 answers

0
tantuni On

The following macro solves not only 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