Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Julia, how to define operator for more than 2 structs?

In Julia, I have my own struct, say MyNumber. I would like to define an operator, e.g. the product operator *, for my struct. The following is what I tried.

struct MyNumber
    name::String
    value::Int
end

x1 = MyNumber("postive", 4)
x2 = MyNumber("postive", 3)

# define product operator for MyNumber
a::MyNumber * b::MyNumber = MyNumber("no_name", a.value + b.value)

y = x1*x2
println(y) # ok here, output: MyNumber("no_name", 7)

It works very well. However, when I try I apply the product for more than 2 inputs, e.g. z=x1*x2*x1*x2*x2, I got error. How do I deal with such case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is the correct way of defining the * operatör for the custom data type:

import Base.:*

struct MyNumber
    name::String
    value::Int
end

x1 = MyNumber("postive", 4)
x2 = MyNumber("postive", 3)

# define product operator for MyNumber
Base.:*(a::MyNumber, b::MyNumber)::MyNumber = MyNumber("no_name", a.value + b.value)

y = x1*x2
println(y) # ok here, output: MyNumber("no_name", 7)

The operator should be imported from the Base package explicitly.

Edit: Since I have used the Base.:* in the method definition, it is not needed to import the operator explicitly as mentioned below.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading