在 Julia 中定义一个继承自向量的类型

发布于 2025-01-10 23:43:06 字数 454 浏览 1 评论 0原文

我想创建一个行为与 Vector 完全相同的类型(例如 my_vector),以便我可以将其传递给所有采用 Vector 的函数。除此之外,我想专门为 my_vector 创建特殊函数,这些函数不适用于通用向量。

因此,例如,如果 AMatrix 并且 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你如我软肋 2025-01-17 23:43:06

这一般是不可能的。

您可以做的是将 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文