Does list.diff( Nil) copy or return list

When I looked at the code for diff and the documentation, it was not clear to me whether diff returns the original list or a copy of it when trying to subtract an empty list. I have a recursive function which tries to reuse tails as much as possible by newItem::origList but sometimes I need to filter the origList.
My code would be prettier if I could assume that diff returns the original list if its second argument is empty.

      else {
        val superTypes = lineage.filter(sup => t.subtypep(sup).contains(true))
        if (superTypes.isEmpty)
          extendPN(bdd, t :: lineage) // avoid allocating a new list
        else
          extendPN(bdd, t :: (lineage diff superTypes))
      }

I could replace this with

      else {
        val superTypes = lineage.filter(sup => t.subtypep(sup).contains(true))
        extendPN(bdd, t :: (lineage diff superTypes))
      }

Of course I could write my own version, but isn’t this something that the standard library function should guarantee?

Looking at the current implementation, it iterates over all elements in the list. There is no good reason for that and should be fixed.

In the mean time, depending on your performance demands, you can either use what you have now, or re-implement diff.

1 Like