Assign a reference to an object, not an object

I had a problem with bindings in Julia When trying to do this:

type Chain
    value :: Int
    son :: Chain

    #Make the last link in the chain point to itself
    #so as to spare us from the julia workaround for nulls
    Chain(value::Int) = (chain = new(); chain.value = value; chain.son = chain; chain)
end

#Create three separate nodes
c=Chain(5)
d=Chain(2)
e=Chain(1)

#Link an object to another and then modify the linked object
c.son = d
son = d.son
son = e
c

I would like to change the link for the son in the parent, but it only works if I do this:

c.son = d
d.son = e
c

This creates a problem in recursive functions, where if you pass an object to a function associated with another object and change it in the body of the function, then the link will not be changed, but only the object itself.

I tried using the julia function pointer_from_objref, but it was used to handle c-functions, and assigning with unsafe_store!did not work.

How can I create a variable that, when assigned, also changes the link that I referenced?

+4
source share
1 answer

, son Array = > son::Array{Chain,1} .

type Chain
    value::Int
    son::Array{Chain,1}
    Chain(value::Int) = (chain = new(); chain.value = value; chain.son = [chain]; chain)
end

julia> c=Chain(5)
Chain(5,[Chain(#= circular reference =#)])

julia> d=Chain(2)
Chain(2,[Chain(#= circular reference =#)])

julia> e=Chain(1)
Chain(1,[Chain(#= circular reference =#)])

julia> c.son = [d]
1-element Array{Chain,1}:
 Chain(2,[Chain(#= circular reference =#)])

julia> son = d.son
1-element Array{Chain,1}:
 Chain(2,[Chain(#= circular reference =#)])

julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])

julia> c
Chain(5,[Chain(2,[Chain(1,[Chain(#= circular reference =#)])])])

, , son = d.son son = e, .

# NOT using array type
julia> son = d.son
Chain(2,Chain(#= circular reference =#))

julia> son = e
Chain(1,Chain(#= circular reference =#))

julia> son === d.son
false

# using array type
julia> son = d.son
1-element Array{Chain,1}:
 Chain(2,[Chain(#= circular reference =#)])

julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])

julia> son === d.son
true

, . .

+2

Source: https://habr.com/ru/post/1610120/


All Articles