This is not a very good use case for meta programming.
Here are two version using dicts and arrays:
https://gist.github.com/SimonDanisch/c01235254451f8234e29

Am Sonntag, 16. November 2014 22:09:57 UTC+1 schrieb Greg Plowman:
>
> Hi
>  
> I'm trying to automate some code and thought Julia's metaprogramming might 
> help, but I've got myself very confused.
>  
> I have a user-defined composite type, which for different applications, I 
> change the fields.
> I also want to define some functions for this user type (+, copy, == etc)
> because I change the composite fields regularly, I thought I could 
> somehow use Julia's introspection / metaprogramming to define these 
> functions.
>  
> Suppose I define:
>  
>
> type Counters
>     counter1::Array{Int64,1}
>     counter2::Array{Int64,1}
>     counter3::Array{Int64,1}
>     counter4::Array{Int64,1}
>     counter5::Array{Int64,2}
>  
>     # no-argument constructor
>     function Counters()
>         this = new()
>         this.counter1 = zeros(Int64, 100000)
>         this.counter2 = zeros(Int64, 100000)
>         this.counter3 = zeros(Int64, 100000)
>         this.counter4 = zeros(Int64, 500)
>         this.counter5 = zeros(Int64, 500, 1000)
>         return this
>     end
> end
>
>  
>  
> Defined explicitly, my + function would look something like:  
>  
>
> function +(c1::Counters, c2::Counters)
>     c = Counters()
>     c.counter1 = c1.counter1 + c2.counter1
>     c.counter2 = c1.counter2 + c2.counter2
>     c.counter3 = c1.counter3 + c2.counter3
>     c.counter4 = c1.counter4 + c2.counter4
>     c.counter5 = c1.counter5 + c2.counter5
>     return c
> end
>
>  
>  
> I was hoping I could define implicitly using macros / metaprogramming:
>  
>
> function +(c1::Counters, c2::Counters)
>     c = Counters()
>     
>     for field in names(Counters)
>         ex = :(c.$field = c1.$field + c2.$field)
>         eval(ex)
>     end
>     
>     return c
> end
>
>  
> I know this doesn't work, but I've tried many variations but always seem 
> to get stuck.
> I would like the function to be eval-ed and unrolled at compile time, so 
> that it executes fast at run time.
>  
> Can someone point me in the right direction?
>  
> Thanks, Greg
>
>

Reply via email to