Skip to content

Instantly share code, notes, and snippets.

@masak

masak/article.md Secret

Created July 26, 2015 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/b694a4050f4e91bd254c to your computer and use it in GitHub Desktop.
Save masak/b694a4050f4e91bd254c to your computer and use it in GitHub Desktop.
deepclone/eqv/perl onramp p6doc explanation

Simple stuff

Sometimes you want to compare structures. Like arrays.

[1, 2, 3] eqv [1, 2, 3];        # True
[1, 2, 3] eqv [1, 4, 3];        # False

Or objects.

my $o1 = C.new(:x(1), :y(2));
my $o2 = C.new(:x(1), :y(2));
my $o3 = C.new(:x(7), :y(2));

$o1 eqv $o2;                    # True
$o1 eqv $o3;                    # False

Or combinations of arrays and objects.

my $o4 = C.new(:x[1, 2, 3]);
my $o5 = C.new(:x[1, 2, 3]);
[$o4, $o5] eqv [$o4, $o5];      # True
[$o4, $o5] eqv [$o5, $o4];      # True
$o4 eqv $o5;                    # True

The way to think about all these is that the objects and arrays don't have to have the same reference in order to match, but they need to have the same contents, all the way down to the leaves.

Deep cloning

tbd; Deep cloning produces a new object graph (but "tree" at this point, before we get to the complications) with each non-leaf reference type being cloned

Shared subtrees

my $o1 = C.new(:x(7));
my $a = [$o1, $o1];
[$a, $a].deepclone;

tbd; in the above, $o1 is cloned exactly once, and then placed in the four positions in the (cloned) nested arrays. In other words, "shared" subtrees in the object tree are taken care of once, and then inserted in the right place.

tbd; .perl also takes this into account. If you have the same reference twice in there, .perl indicates this by (the first time) assigning to a variable and (subsequent times) showing the variable. (Data::Dumper already works this way.)

Cycles

tbd; If an ancestor occurs nested in a descendant, we have a cycle. These are handled in much the same way: clone only once, .perl and eqv DTRT without getting in an infinite tissy

The cycle detection mechanism

tbd; If we want to expose the way cycle detection is done in object graphs, this is where we describe that.

What to think about when implementing your own class

tbd; Here we describe the default behavior you get for .perl, eqv, and deepclone. Then we also describe how and when you might want to override it.

tbd; It is especially important that we think about common cases when you might want to have an opaque object, that doesn't compare any attributes at all, and eqv reduces to reference comparison. Also probably important to think about when we want some attributes to figure in the eqv comparison/deepcloning/.perl but not others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment