The minimum working case would be: Let say I have a vector of mixed types:
x = [ isodd(i) ? rand(Int64) : rand(Float64) for i in 1:1000 ]
I want to sum these numbers, with:
function mysum(x)
s = 0.
for val in x
s += val
end
s
end
This turns out to the be slow because of the type instability of the numbers and the runtime dispatch associated with it. This version which splits the calculations for each type runs much faster and does not allocate:
function mysum_fast(x)
s = 0.
for val in x
if val isa Int64
s += val
elseif val isa Float64
s += val
end
end
s
end
Now if instead of two types of numbers, I had dozens of different types, writing that function would be very annoying. Seems the place for a macro.
Given a list of the types:
types = [ Int64, Float64 ]
I guess a simple macro can generate the mysum_fast
function for me. Seems that should be simple, but I have a hard time understanding the manual on this part. In particular I could not find how to concatenate two expressions, something that I have the impression that would be required to write such macro (generate the expression of the beginning of the loop, loop over the types concatenating the conditionals, concatenate the closing of the loop).