Set

From CometPublic

Jump to: navigation, search

This is the class that supports sets of integers declared with statements like

  set{int} x();

Sets can also be initialised as they as declared like

 set{int} x = {1,2,3};

You can also create sets by using the collect construct

 set{int} x = collect(i in 1..10) i;
 set{int} y = {1,2,3,4,5,6,7,8,9,10}; // equivalent but obviously less preferable for large ranges.

Collect can also be used to collect the results of expressions

 range r = 1..12;
 set{int} x = collect(i in r)(i + i^2);

The setof operator is useful for situations when you want to use a boolean expression to capture which values from a range you want. For example this expression catches all the even numbers in the range 1..10.

set{int} x = setof(i in 1..10)(i % 2 == 0);

With this declaration, x is an instance of the class shown below and complies with its API.

   class Set{Int} {
      int getSize(); //Returns the cardinality of the set
      int getLow(); //Returns the smallest int of the set
      int getUp(); //Returns the largest int of the set
      int atRank(int); //Returns the integer at this rank (rank of first element is 0). If the rank is greater or equal to the cardinality, an error is raised.
      int getRank(int); //Returns the rank of an integer (rank of first element is 0). If it is not part of the set, an error is launched.
      bool contains(int); //Tells if the set contains a particular integer
      void insert(int); //insert an int in the set.
      void delete(int); //remove an int from the set.
      void del(int); //if an element has been inserted several times, it is decremented of one occurence.
      void updateMax(int); 
      void updateMin(int);
      Set{Int} copy(); //Returns a copy of the set
      int compare(Set{Int}); // lexographic comparison, returns 0 if sets are equal, -1 if set is lexographically smaller the argument and 1 otherwise. 
      void empty(); //Empties the set
   }

For instance, a statement like

  x.insert(5);

On an empty set x, will produce the singleton {5}.