RFD: CountedSet

I think one guiding principle here would be to try to ensure that algorithms written for SetAlgebra generally behave reasonably when used with a CountedSet. There is a heavier focus on (correct) generic algorithms in Swift than there was in Objective-C, so the design might end up in a different place to NSCountedSet. Or perhaps CountedSet shouldn't conform to SetAlgebra at all?

Yes, I like the practical example of an RPG inventory to anchor the proposal. I'm not sure it points to set-like being more useful though. Questions like “Does this user have enough of each ingredient to make this potion?” [subset] and the examples from my previous post (“Add all the items from this chest to your inventory” [addition], “subtract all the items you sold to the store” [subtraction]) are more counted-like.

Union and intersection are trickier to know what to do with. My assumption is that sticking to the mathematical definitions would preserve more of the semantics of SetAlgebra. “Add the arrows from this quiver to that quiver” seems more naturally covered by addition than union (though there is a potential for confusion because they are essentially the same for Set). If I understand “What arrows and magnitude appear in both” correctly, then this is the multiset definition of intersection (the minimum count over all elements from both sets).

Sure, a count is required for SetAlgebra, but which definition? As I said, I think defining it as the cardinality of the multiset is more compatible with the semantics of SetAlgebra, if conformance to SetAlgebra is a goal.

The set-like vs counted-like divide that you mention is a good way to think about it. If it's the latter then we can probably just take the multiset definitions directly, but if it's the former then we have to think about what happens to the counts during every SetAlgebra operation. Are they added together? Subtracted? Max? Min? Just preserved from self? I'm not sure yet how to make that decision in a principled way, and I'm not convinced that there's always a right answer that makes sense for all uses of CountedSet.

Perhaps CountedSet itself could follow multiset definitions, but provide a Set view of the elements so you can also easily do set-like operations when you want to ignore the counts (e.g. “Does this user have at least this core group of arrows in his quiver”).

1 Like