在 Julia 中定义一个继承自向量的类型
我想创建一个行为与 Vector 完全相同的类型(例如 my_vector
),以便我可以将其传递给所有采用 Vector 的函数。除此之外,我想专门为 my_vector
创建特殊函数,这些函数不适用于通用向量。
因此,例如,如果 A
是 Matrix
并且 typeof(b)
是 my_vector
,我想成为能够使用 A\b
求解线性系统,使用 length(b)
恢复其长度,或使用 b[index]
访问其元素代码>.
同时,我想定义一个特定的函数,它可以接受 my_vector
类型的对象作为参数,但不接受 Vector
类型的对象。
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一般是不可能的。
您可以做的是将
my_vector
类型定义为AbstractVector
的子类型。那么所有接受AbstractVector
的函数也将接受您的类型。 https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array。然后,如果您希望您的
my_vector
类型也具有Vector
具有但AbstractVector
没有的功能,您需要自己实现以下函数的方法:专门定义为仅接受Vector
。 Julia 标准安装中有 49 个这样的方法,您可以通过编写methodswith(Vector)
找到它们的列表。您很可能不需要全部这些方法,而只需选择一小部分此类方法,例如push!
或pop!
。话虽如此,这并不能确保接受
Vector
的所有内容都会接受您的my_vector
,就好像某些包只接受Vector
您必须执行对于此包中定义的函数,过程相同。总而言之 - 检查
AbstractVector
是否足以满足您的需求(很可能是这样),然后就很简单了。如果不是这样,那么做你想做的事就很难了。This is not possible in general.
What you can do is define your
my_vector
type as subtype ofAbstractVector
. Then all functions acceptingAbstractVector
will also accept your type. What you need to implement forAbstractVector
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 thatVector
has butAbstractVector
does not have you need to implement yourself methods for functions that are specifically defined to only acceptVector
. There are 49 such methods in Julia standard installation and you can find their list by writingmethodswith(Vector)
. Most likely you will not need them all but only a small selection of such methods e.g.push!
orpop!
.Having said that this will not ensure that everything that accepts
Vector
will accept yourmy_vector
, as if some package accepts onlyVector
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.