In my algorithm I need to maintain a set (an unordered list of distinct elements) of expressions supporting two operations:
- Test an expression for membership in the set
- Adding a new expression to the set
Expressions are to be compared using SameQ. The set can have hundreds of thousands of elements and I want it to work as fast as possible. In most programming languages I would use a hash-table or a balanced tree to implement such a set. Is there any better data structure in Mathematica for this purpose than a plain List? Is it worth trying to manually implement a better structure?
DownValues, just by introducing some symbol (say,presentQ). Starting definition ispresentQ[_]=False. Then,adding is as simple aspresentQ[expr] = True, andpresentQitself tests for membership. This seems the easiest option. You can also useSystem`Utilities`HashTableas an alternative. $\endgroup$SubValues, although the difference is mostly syntactic. But I have not seen a clear exposition in the documentation which would have explained that hash table functionality in Mathematica is most easily achieved viaDownValues. $\endgroup$expris a pattern, the plainpresentQ[expr] = Truedoes not have the intended meaning. The fix is to usepresentQ[Verbatim[expr]] = Trueinstead. $\endgroup$