Thanks Kevin!

Haven't thought of reinterpret in this context, very elegant solution for 
array of omposites - composite of arrays type of problems.

Cheers,
Kaj


On Tuesday, January 12, 2016 at 8:04:26 PM UTC+2, Kevin Squire wrote:
>
>
> Hi Jon,
>
> On Tue, Jan 12, 2016 at 8:53 AM, David P. Sanders <[email protected] 
> <javascript:>> wrote:
>
>> El martes, 12 de enero de 2016, 10:36:50 (UTC-6), Jon Norberg escribió:
>>>
>>> I would like to create a composite type and then also create an array 
>>> that has values from this type by reference. The behaviour I am looking for 
>>> is like this:
>>>
>>> type c
>>>   a::Float64
>>>   b::Float64
>>> end
>>>
>>> x=c(0.1,0.2)
>>> y=c(0.3,0.4)
>>>
>>> z=[x.a,x.b,y.a,y.b]
>>>
>>> show(z)
>>> [0.1,0.2,0.3,0.4]
>>>
>>> x.a=0.5
>>>
>>> show(z)
>>> [0.5,0.2,0.3,0.4]
>>>
>>> z[4]=0.6
>>>
>>> show(y.b)
>>> 0.6
>>>
>>> Is this possible?
>>>
>>
>>
>> You can get this effect by creating an array of the two objects (rather 
>> than of their components, which doesn't make much sense anyway):
>>
>> julia> type MyType
>>        a::Float64
>>        b::Float64
>>        end
>>
>> julia> x = MyType(1, 2)
>> MyType(1.0,2.0)
>>
>> julia> y = MyType(3, 4)
>> MyType(3.0,4.0)
>>
>> julia> z = [x, y]
>> 2-element Array{MyType,1}:
>>  MyType(1.0,2.0)
>>  MyType(3.0,4.0)
>>
>> julia> x.a = 10
>> 10.0
>>
>> julia> z
>> 2-element Array{MyType,1}:
>>  MyType(10.0,2.0)
>>  MyType(3.0,4.0)
>>
>
> For the array itself, it is possible to view it in multiple ways using 
> immutable and reinterpret.  But mimicking the answers above, it's not 
> possible to directly get a reference to the object (and even if it was, you 
> couldn't modify the individual parts of the object with that reference, 
> because here, it's immutable).
>
> julia> immutable C
>            a::Float64
>            b::Float64
>        end
>
> julia> z = [C(0.1,0.2), C(0.3,0.4)]
> 2-element Array{C,1}:
>  C(0.1,0.2)
>  C(0.3,0.4)
>
> julia> z_view = reinterpret(Float64, z)
> 4-element Array{Float64,1}:
>  0.1
>  0.2
>  0.3
>  0.4
>
> julia> z_view[4] = 0.6
> 0.6
>
> julia> z
> 2-element Array{C,1}:
>  C(0.1,0.2)
>  C(0.3,0.6)
>
> julia> z[1] = C(1.0, 2.0)
> C(1.0,2.0)
>
> julia> z_view
> 4-element Array{Float64,1}:
>  1.0
>  2.0
>  0.3
>  0.6
>
> Cheers,
>    Kevin
>

Reply via email to