我想创建一个包含Point2D成员x和y的复合类型,这很容易。但我希望它能参与非Point2D的正常数学函数,例如,Point2D(1,2) + [1,1]应该会产生一个值的Vector{Int64} [2,3]。
我创建了基于convert和promote_rule的朱莉娅的转换()什么时候使用?和promote_rule函数,但是后来意识到我的类型需要是convert编辑的一个子类型。但是,当我试图从Vector或Vector{T}或任何类型的Array或AbstractArray中进行子类型以使我的类型参与转换时,我就得到了ERROR: invalid subtyping in definition of Point2D。如果作为一个实验,我将我的类型设置为Number的一个子类型,就像在type Point2D{T} <: Number中一样,那么至少文件没有错误地加载,但是当然,当我尝试Point2D(1,2) + [1,1]时,我得到了ERROR: no promotion exists for GridCalc.Point2D{Int64} and Int64。
我还试着把我的Point2D变成mutable struct,但它也不会“拿走”<: Vector{T}。
以下是代码:
type Point2D{T} # Fails when I add <: Vector{T}, etc.
x::T
y::T
end
# Convert a Point2D to a vector of the same type
convert{T1, T2<:Vector{T1}}(::Type{T2}, p::Point2D{T1}) = [p.x, p.y]
# Choose Vector when given the option
promote_rule{T1<:Real, T2<:Point2D{T1}, T3<:Vector{T1}}(::Type{T2}, ::Type{T3}) = T3问题:
Point2D像2向量一样参与数学函数的正确方法吗?Point2D成为Vector{T}的一个子类型发布于 2017-07-17 04:45:34
这样做的方法是子类型AbstractVector{T}。在朱莉娅中,您只能使用子类型抽象类型;Vector{T}是一个具体类型。您还必须实现一些必需的方法。有关更多细节,请参见接口章节:
julia> type Point2D{T} <: AbstractVector{T}
x::T
y::T
end
Base.getindex(p::Point2D, i::Int) = getfield(p, i)
Base.size(::Point2D) = (2,)
julia> Point2D(1,2)
2-element Point2D{Int64}:
1
2
julia> [1 2; 3 4; 5 6] * Point2D(1,2)
3-element Array{Int64,1}:
5
11
17您还可以查看(和/或使用) JuliaGeometry组织和GeometryTypes.jl的点定义和周围方法。
https://stackoverflow.com/questions/45135765
复制相似问题