Next: Tables Up: Data Structures Previous: Sequences

Lists and Sets

Lists, sets and functions are constructed from sequences. A list is a data structure for collecting objects together. Square brackets are used to create lists, for example


> l := [x,1,1-z,x];
                             l := [x, 1, 1 - z, x]

> whattype(l);

                                      list

The empty list is denoted by []. Sets can also be used to collect objects together. The difference between lists and sets is that duplicates are removed from sets. Squiggly brackets are used for sets, for example


> s := {x,1,1-z,x};
                               s := {1, 1 - z, x}

> whattype(s);
                                      set

The empty set is denoted by {}. The nops function returns the number of elements of a list or set and the op function extracts the 'th element. You can also use the subscript notation to access the 'th element of a sequence, list or set. For example,


> op(1,s);
                                       1

> s[1];
                                       1

> op(1..3,s);
                                  1, 1 - z, x

> s[1..3];

                                  1, 1 - z, x

Here is a loop that prints true if a list or set contains the element , and false otherwise.


for i to nops(s) while s[i] <> x do od;
if i > nops(s) then print(false) else print(true) fi;

The built in member function does this for you. member(, ) returns true if the element is in the list or set . You can append a new element to a list l by doing


l := [op(l),x];

You can remove the 'th element of a list by doing


l := [ l[1..i-1], l[i+1..nops(l)] ];

Or, better, use the subsop function


l := subsop(i=NULL,l);

The subsop function note can be used for any type of expression. The set operators are union, intersect and minus, e.g.


> t := {u,x,z};
                                 t := {x, z, u}

> s union t;
                                  {x, z, y, u}

The Maple user will probably have noticed that Maple orders the elements of sets in a strange order which seems to be unpredictable. The algorithms that Maple uses to remove duplicates, and to do set union, intersection and difference all work by first sorting the elements of the input sets. Maple sorts by machine address, i.e. in the order that the elements occur in computer memory. Since this depends on where they are put in memory, this is why the order is strange and unpredictable. The reason Maple sets are implemented in this way is to make the set operations very fast.


bondaren@thsun1.jinr.ru