Set: Difference between revisions

Content added Content deleted
m (Added a general comment at the beginning to present the sets and also the HashSets.)
(Added an example with HashSet. Added reference to OrderedSet and module "intsets".)
Line 3,534: Line 3,534:
s.incl(4) # add 4 to set
s.incl(4) # add 4 to set
s.excl(5) # remove 5 from set</lang>
s.excl(5) # remove 5 from set</lang>

HashSets are not very different, less efficient but more versatile. Here is the same program with HashSets. The only difference is the way to create a HashSet: this is done by converting an array or sequence to the HashSet. As there is no way to specify a range in an array, we use a conversion of range to sequence with “toSeq” and a union.

<lang Nim>import sequtils, sets

var # creation
s = [0, 3, 5, 10].toHashSet
t = toSeq(3..20).toHashSet + toSeq(50..55).toHashSet

if 5 in s: echo "5 is in!" # element test

var
c = s + t # union
d = s * t # intersection
e = s - t # difference

if s <= t: echo "s ⊆ t" # subset

if s < t: echo "s ⊂ t" # strong subset

if s == t: echo "s = s" # equality

s.incl(4) # add 4 to set
s.excl(5) # remove 5 from set</lang>

Note that there exists also an Ordered constructor which remembers the insertion order. And for sets of integers, the module “intsets” provides another constructor better suited for sparse integer sets.


=={{header|Objective-C}}==
=={{header|Objective-C}}==