Julia: perform standard math operations on types

Is there a way to implement basic arithmetic for user-created types in julia

For instance:

type Foo bar::Float32 foo::Int32 end a = Foo(3.23,23) b = Foo(4.56,54) c = a+b 

How, if at all possible, can I do this? thanks in advance

+2
source share
1 answer

You need to explicitly import the base functions to add methods to them for your own types. I'm not sure if this is the best way to do this, but the following will allow you to add two Foos together.

 type Foo bar::Float32 foo::Int32 end import Base: + +(a::T, b::T) where {T<:Foo} = Foo(a.bar+b.bar, a.foo+b.foo) a = Foo(3.23,23) b = Foo(4.56,54) c = a+b 
+10
source

Source: https://habr.com/ru/post/1273615/


All Articles