julia> type MyType a_1::Float64 a_2::Float64 end
julia> using Base.Cartesian julia> function plus(m1::MyType, m2::MyType) @nexprs 2 d->(s_d = m1.a_d + m2.a_d) MyType(s_1, s_2) end plus (generic function with 1 method) julia> m1 = MyType(1,2) MyType(1.0,2.0) julia> m2 = MyType(0.3,0.8) MyType(0.3,0.8) julia> plus(m1,m2) MyType(1.3,2.8) See the "Developer docs" Base.Cartesian. --Tim On Sunday, November 16, 2014 02:39:01 PM Simon Danisch wrote: > 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