Julia:自指代和递归类型

问题描述 投票:0回答:2

我想做的不是很简单,如果我从结果开始然后解释我如何去那儿,也许会更容易。

我有一个带有两个字段的结构:

struct data{T}
    point::T
    mat::Array
end

我想做的就是将其嵌套,并使场垫自指以得到如下内容:

data{data{Int64}}(data{Int64}(1, [1]), [1])

'外部'类型不应存储[1],而应引用最里面的垫子。我不确定这是否有意义甚至可能。现场垫应重复存储相同的大数组。

我已经尝试过类似的事情(n是嵌套类型的数量。

struct data{T}
    point::T
    g::Array
    function D(f, g, n)
        for i = 1:n
            (x = new{T}(f, g); x.f = x)
        end
    end
end 

同样,我不确定我是否足够了解自指构造函数,或者是否有可能。任何帮助/澄清将不胜感激,谢谢!

data-structures struct julia self-reference
2个回答
0
投票

根据您的描述,data看起来很普通。也许您可以尝试这样的事情:

mutable struct Wrap{T}
    w::Wrap{T}
    d::T
    function Wrap(d::T) where T
        w = new{T}()
        w.d = d
        w
    end
end

function Wrap(d, n::Int)
    res = Wrap(d)
    cur = res
    for _ in 1:n-1
        cur.w = Wrap(d)
        cur = cur.w
    end
    res
end

Wrap([1], 4)
# Wrap{Array{Int64,1}}(Wrap{Array{Int64,1}}(Wrap{Array{Int64,1}}(Wrap{Array{Int64,1}}(#undef, [1]), [1]), [1]), [1])

0
投票

确切的模式将取决于您要实现的目标,但这是一个示例:

struct Data{V, A <: AbstractArray{V}, T} 
    mat::A
    point::T

    Data(mat::A, point::T = nothing) where {V, A <: AbstractArray{V}, T} =
        new{V,A,T}(mat,point)
end

用法

julia> d0 = Data([1,2,3])
Data{Int64,Array{Int64,1},Nothing}([1, 2, 3], nothing)

julia> d1 = Data([1.0,2.0],d0)
Data{Float64,Array{Float64,1},Data{Int64,Array{Int64,1},Nothing}}([1.0, 2.0], Data{Int64,Array{Int64,1},Nothing}([1, 2, 3], nothing))

© www.soinside.com 2019 - 2024. All rights reserved.