A set stores distinct elements without giving them positions. Use one when the question is “Does this item belong here?” or “Which items match these categories?” rather than “What is at index 2?” In Julia, `Set([3, 3, 3, 1, 2])` contains just three elements. You can iterate over a set, but you cannot rely on its iteration order or access an element by array index. section 13.2 section 13.2.1
Table 13.1 Differences and similarities between sets and arrays (view table figure)
Compare sets and arrays at a glance: both are iterable, but only sets exclude duplicates and offer quick membership tests; only arrays preserve positional order and support indexed access. section 13.2.1
Start with the operation that matches your question:
- Test membership with `x in S` or `in(x, S)`. Sets make this quick; searching an unsorted array requires checking its elements. section 13.2.1 section 13.8
- Use `intersect` for items shared by categories, `union` to combine categories, and `setdiff` to exclude one category from another. section 13.5 section 13.8
- Convert an array to a set to remove duplicates: `length(Set([1, 1, 2, 2, 3]))` is `3`. Choose an array instead when duplicates or element positions matter. section 13.2.1
Find products matching several criteria
Suppose each product has a unique number, and separate sets hold the numbers for rounded heads, torx drives, and wood material. `intersect(rounded, torx, wood)` returns numbers present in all three sets. `setdiff(tslot, plastic)` finds T-slot products that are not plastic. These overlapping categories are easier to combine than to force into a single category tree. section 13.1 section 13.5
Sets can also work alongside richer records. Filter product objects into reusable sets, or keep product numbers in sets and use a dictionary to retrieve the corresponding objects. The same pattern fits a bug tracker: intersect sets of bug numbers by assignee, severity, and project. A sorted array with binary search or filtering an array may also fit a problem, but the tradeoffs differ: sorted arrays must stay sorted, while array filtering is less attractive for large datasets. section 13.5.4 section 13.5.5 section 13.6 section 13.2.1














