Define a type that inherits from a vector in Julia

417 Views Asked by At

I would like to create a type (say, my_vector) that behaves exactly like a Vector, so that I can pass it to all the functions that take Vectors. In addition to that, I want to create special functions exclusively for my_vector, that do not work for generic Vectors.

So, for instance, if A is a Matrix and typeof(b) is my_vector, I want to be able to solve a linear system using A\b, to recover its length with length(b), or to access its elements with b[index].

At the same time, I want to define a specific function that can take objects of type my_vector as parameters, but that does not take objects of type Vector.

How can I do this?

1

There are 1 best solutions below

2
On

This is not possible in general.

What you can do is define your my_vector type as subtype of AbstractVector. Then all functions accepting AbstractVector will also accept your type. What you need to implement for AbstractVector is listed in https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array.

Then if you want your my_vector type to also have functionalities that Vector has but AbstractVector does not have you need to implement yourself methods for functions that are specifically defined to only accept Vector. There are 49 such methods in Julia standard installation and you can find their list by writing methodswith(Vector). Most likely you will not need them all but only a small selection of such methods e.g. push! or pop!.

Having said that this will not ensure that everything that accepts Vector will accept your my_vector, as if some package accepts only Vector you will have to perform the same process for functions defined in this package.

In summary - check if AbstractVector is enough for you, as most likely it is and then it is simple. If it is not the case then doing what you want is difficult.