Links(), old code, and sets vs.lists

I was reviewing/annotating code in a long-lived file and saw this:

$CoAuthors = (links(this).outbound."Authored".$Authors)-$Name;

which gives me a listing of all the contributing authors ($Authors) in papers to which this not links via an “Authored” type of link. as the code runs in a note about a given author, we subtract their name as they can’t be their own co-author. Spotted the error yet?

Though links() used to return a Set (it got added in v4.0.0), from v5.8.0 is changed to returning a List. Sets de-dupe but links don’t. Now see the error?

So if the same co-author appears in more than one linked paper they will be returned multiple times. That calls for a test. so I made one. The key test was to make sure that the note we test—“John Doe”—links to several notes and at least one co-author occurs more than once. Thus

Note hew the old code results in an overcount of three. This is because co-author ‘Joan Gee’ is listed twice. Also deleting John Doe’s name removes only one of the 3 instances of his name (he authored 3 papers).

Here, as it is easier to read the lists in $Text, I used variables for the list, bUt, I could have created a $MyList2 and made both Displayed Attributes (setting the attributes do display on several lines as allowed in v9.6.0+.

So, the fix is to de-dupe the list using .unique making sure only one instance of each name remains. then, we delete the current author from the list. You could use replace but this doesn’t involve using a regex so is less load at scale (my data is a big TBX). Sets self-sort but Lists don’t so we also add a .sort call. No harm was done by the original as any human looking at the data would have discounted the dupes. But, had I been, for example, been calculating the average number of co-authors across all authors, i might have been embarrassed.

So my hunch was right and it shows that even though I wrote this document in the app in v6 onwards, I’d missed a pertinent change from the v5.x era. So, it pays to review code occasionally!

Here’s the test document (the action above is the $Edict for note ‘John Doe’) in case you’d like to experiment:

links test 1.tbx (156.9 KB)

Now I’ve some code to fix…

†. This is why having the old versions of aTbref can be useful, otherwise this sort of historical check would be really hard. :slight_smile:

1 Like