sets_fragment.txt 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. The set type models the mathematical notion of a set. The set's basetype can
  2. only be an ordinal type of a certain size, namely:
  3. * ``int8``-``int16``
  4. * ``uint8``/``byte``-``uint16``
  5. * ``char``
  6. * ``enum``
  7. or equivalent. The reason is that sets are implemented as high
  8. performance bit vectors. Attempting to declare a set with a larger type will
  9. result in an error:
  10. .. code-block:: nim
  11. var s: set[int64] # Error: set is too large
  12. Sets can be constructed via the set constructor: ``{}`` is the empty set. The
  13. empty set is type compatible with any concrete set type. The constructor
  14. can also be used to include elements (and ranges of elements):
  15. .. code-block:: nim
  16. type
  17. CharSet = set[char]
  18. var
  19. x: CharSet
  20. x = {'a'..'z', '0'..'9'} # This constructs a set that contains the
  21. # letters from 'a' to 'z' and the digits
  22. # from '0' to '9'
  23. These operations are supported by sets:
  24. ================== ========================================================
  25. operation meaning
  26. ================== ========================================================
  27. ``A + B`` union of two sets
  28. ``A * B`` intersection of two sets
  29. ``A - B`` difference of two sets (A without B's elements)
  30. ``A == B`` set equality
  31. ``A <= B`` subset relation (A is subset of B or equal to B)
  32. ``A < B`` strong subset relation (A is a real subset of B)
  33. ``e in A`` set membership (A contains element e)
  34. ``e notin A`` A does not contain element e
  35. ``contains(A, e)`` A contains element e
  36. ``card(A)`` the cardinality of A (number of elements in A)
  37. ``incl(A, elem)`` same as ``A = A + {elem}``
  38. ``excl(A, elem)`` same as ``A = A - {elem}``
  39. ================== ========================================================
  40. Sets are often used to define a type for the *flags* of a procedure. This is
  41. a much cleaner (and type safe) solution than just defining integer
  42. constants that should be ``or``'ed together.