[Gambas-user] some questions around collections copy and collections inside collections

Tobias Boege taboege at ...626...
Tue Sep 6 22:19:37 CEST 2016


On Tue, 06 Sep 2016, PICCORO McKAY Lenz wrote:
> i have a function that returns a collections of collections, named
> getPedidogeneral
> 
> i mean, this function returns object coll1 that inside each key is a id of
> a object that also are a collection too
> 
> i try to copy the firts to other, i mean coll2 = coll1.copy() or coll2 =
> coll1
> 
> i noted that the refers inside coll1 are the same as coll2!
> 
> the problem are that if i modified some keys of the coll1 object, same key
> in the coll2 object also its modified!
> 
> and so the only way to modified each collection without affecting the other
> its obtain a copy with differents references but same contents, so i must
> recall the function for that!
> 
> to ilustrate i posted a image
> 

That is the expected behaviour. Copying coll1 should create a new Collection
with exactly the same contents, i.e. a /shallow/ copy of the Collection, as
opposed to a /deep/ copy in which all contents of coll1 would also have been
copied recursively.

There's something called Rice's Theorem which forbids the existence of a
general algorithm which can create a deep copy of any Gambas object [*].
Since a Collection may hold any object, it is impossible to create deep
copies of Collections, *in general*.

Of course, if you know that your Collection only contains Collections, which,
in turn, you are sure only contain primitive data types (which can easily be
deep-copied), then you can, of course, write a deep copy function:

  '' Assumes ~cCol~ is a Collection of Collections, each of which contains
  '' data of primitive types.
  Private Function CopyMyCollection(cCol As Collection)
    Private cNew As New Collection
    Dim cElt As Collection

    For Each cElt In cCol
      cNew[cCol.Key] = cElt.Copy()
    Next
    Return cNew
  End

Regards,
Tobi

[*] More specifically it follows from Rice that you can't decide if a 64-bit
    word is meant by the program to be a number or a pointer. /If/ a general
    copy routine for objects existed, you could apply it to any given 64-bit
    word and if the copy is different from the original, it must have been a
    pointer (which the copy routine had to deep-copy), and otherwise it must
    have been a number because its value had to be preserved by the copier.
    But because that is undecidable, you get a contradcition.

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list