Re: sequence question
- Posted by Derek Parnell <ddparnell at bigpond.com> Sep 04, 2004
- 482 views
Tone Škoda wrote: > > sequence s1, s2 > s1 = repeat (0, 1000000) -- s1 is 3.8MB big > s2 = {{}} > s2 [1] = s1 > > will this last line of code: > 1. make copy of s1 into s2 [1] > 2. or will it only make pointer to s1? > > similar is this: > s2 = {repeat (0, 1000000)} > s1 = s2 [1] -- what happens here? > > if it is number 1 then it is waste of memory. > in cases like this i like C more because it is more clear what happens. I think, and I stress *think*, what happens is that the 'copied' sequence is just a pointer to the original until such time as the original is changed, then you get a real copy done. All of this happens in the background. sequence s1, s2 s1 = repeat (0, 1000000) -- s1 is 3.8MB big s2 = {{}} s2 [1] = s1 -- s2[1] now points to s1. s1[1] = 1 -- This also triggers a copy of the original s1 -- so that s2[1] now contains (points to actually) a -- copy of s1. > i'm asking this because i want to create a library which is not specific for > program. > and in this library one sequence1 appears in many different sequences. i could > only > have one copy of this sequence1, not many same copies which would exist in > these different > sequences. here pointers would be nice. > > i would like pointers and structures added to euphoria. > pointers are good because you can identify a variable without having to copy > it in > memory. you can do that in euphoria but it's much more complicated. structures > are > also possible in euphoria but again not on simple easy way. and structures are > needed > in every program. The way that I do things so it has the same effect as pointers is that I have a 'global' sequence and pass a 'pointer' to it in the form of an index. eg.
global sequence PH PH = {} sequence PHalloced PHalloced = {} global function allocPH() integer lPos lPos = find(0, PHalloced) if lPos then PHalloced[lPos] = 1 return lPos end if PH &= 0 PHalloced &= 1 return length(PHalloced) end function global procedure freePH(integer pPos) if pPos > 0 and pPos <= length(PH) then PH[pPos]=0 PHalloced[pPos] = 0 end if end procedure global function isAllocedPH(integer pPos) if pPos > 0 and pPos <= length(PH) then return (PHalloced[pPos] != 0) else return -1 end if end function integer x sequence s1,s2 x = allocPH() PH[x] = repeat(0, 1000000) s1 = {x} -- points to sequence s2 = {x} -- points to sequence. PH[ s1[1] ][1] = 1 -- assign using S1 ? PH[ s2[1] ][1] -- read using S1 freePH(x) if isAllocedPH(x) then ? PH[s2[1]][1] else ? 3 end if
So in short, Heap based objects can be passed by reference using this technique. And yes, datatype-safe structures would be nice because the Euphoria would validate the datatype-ness rather than leaving it up to the programmer. -- Derek Parnell Melbourne, Australia