julia> type Foo{T<:Number}
           x::Vector{T}
       end

julia> ops = [+, -, *, /]
4-element Array{Function,1}:
 +
 -
 *
 /

julia> syms = [symbol(op) for op in ops]
4-element Array{Any,1}:
 :+
 :-
 :*
 :/

julia> for sym in syms
           dot_sym = symbol(".$sym")                        # create 
element-wise symbol 
           docstr = "`$sym` also works for `Foo` types!"    # this has to 
be created before `@eval`
           @eval begin
               @doc $docstr ->                              # attach 
docstring
               function Base.$sym(a::Foo, b::Foo)
                   Foo($dot_sym(a.x, b.x))                  # infix 
notation wont work here!
               end
           end
       end

julia> x = Foo([1,2,3])
Foo{Int64}([1,2,3])

julia> y = deepcopy(x)
Foo{Int64}([1,2,3])

julia> for op in ops
           println("$x $op $y = $(op(x, y))")
       end
Foo{Int64}([1,2,3]) + Foo{Int64}([1,2,3]) = Foo{Int64}([2,4,6])
Foo{Int64}([1,2,3]) - Foo{Int64}([1,2,3]) = Foo{Int64}([0,0,0])
Foo{Int64}([1,2,3]) * Foo{Int64}([1,2,3]) = Foo{Int64}([1,4,9])
Foo{Int64}([1,2,3]) / Foo{Int64}([1,2,3]) = Foo{Float64}([1.0,1.0,1.0])

help?> +
search: + .+

  +(x, y...)

  Addition operator. x+y+z+... calls this function with all arguments, i.e.
  +(x, y, z, ...).

  + also works for Foo types!

julia>



El martes, 15 de diciembre de 2015, 10:28:53 (UTC-6), [email protected] 
escribió:
>
> Hello,
>
> I have a type M and I would like to redefine all the operations *, +, -, / 
> etc. over it. Since it would be everytime the same operations and since I 
> want my code to be concise I thought about using a macro to define them, 
> such as:
>
> type M
>     a
>     b
> end
>
> macro operator_obs(name)
>     return quote
>         function $name(m1::M, m2::M)
>             return M($name(m1.a, m2.a), $name(m1.b, m2.b))
>         end
>     end
> end
>
> @operator_obs(+)
>
> m1 = M(2.0,3.0)
> m2 = M(4.0,5.0)
>
> +(m1, m2)
>
> But this doesn't seem to work. What did I do wrong?
>
> Many thanks,
>

Reply via email to