Task

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.



The task should show:

 Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.
 Any limitations of the method.
 That the structure and its copy are different.
 Suitable links to external documentation for common libraries.


 
'DEEP COPY FOR A RECURSIVE TREE STRUCTURE
 
uses console
 
class branches
  '
  static int count
  int level
  int a,b,c
  branches*branch1
  branches*branch2
  '
  method constructor(int n)
  =========================
    level=n
    count++
    output count tab level cr
    if level>0
      new branches n1(n-1)
      new branches n2(n-1)
      @branch1=@n1
      @branch2=@n2
    endif
    ...
  end method
  '
  method destructor
  =================
    if level>0
      del branch1
      del branch2
    endif
    ...
  end method
  '
  method RecurseCopy(int n, branches *dc, *sc)
  ============================================
    dc.level=sc.level
    dc.a=sc.a
    dc.b=sc.b
    dc.c=sc.c
    if n>0
      RecurseCopy n-1, byval @dc.branch1, byval @sc.branch1
      RecurseCopy n-1, byval @dc.branch2, byval @sc.branch2
    endif
  end method
  '
  method DeepCopy() as branches*
  ==============================
    new branches dc(level)
    RecurseCopy level,dc,this
    return @dc
  end method
  '
end class
 
output "count" tab "level" tab "(original)" cr
new branches br(3)
output "count" tab "level" tab "(copy)" cr
branches *bc = br.DeepCopy
pause
del bc
del br
 