31 Ranges

A range is a dense list of integers, such that the difference between consecutive elements is a nonzero constant. Ranges can be abbreviated with the syntactic construct [ first, second .. last ] or, if the difference between consecutive elements is 1, as [ first .. last ].

If first last, [first,second..last] is the empty list, which by definition is also a range. If first = last, [first,second..last] is a singleton list, which is a range too. Note that last - first must be divisible by the increment second - first, otherwise an error is signalled.

Note that a range is just a special case of a list. So everything that is possible for lists (see Lists) is also possible for ranges. Thus you can access elements in such a range (see List Elements), test for membership (see In), etc. You can even assign to such a range (see List Assignment). Of course, unless you assign last + second-first to the entry range[Length(range)+1], the resulting list will no longer be a range.

Most often ranges are used in connection with the for-loop (see For). Here the construct
for var in [first..last] do statements od replaces the
for var from first to last do statements od, which is more usual in other programming languages.

Note that a range is at the same time also a set (see Sets), because it contains no holes or duplicates and is sorted, and also a vector (see Vectors), because it contains no holes and all elements are integers.

    gap> r := [10..20];
    [ 10 .. 20 ]
    gap> Length( r );
    11
    gap> r[3];
    12
    gap> 17 in r;
    true
    gap> r[12] := 25;; r;
    [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25 ]
    gap> r := [1,3..17];
    [ 1, 3 .. 17 ]
    gap> Length( r );
    9
    gap> r[4];
    7
    gap> r := [0,-1..-9];
    [ 0, -1 .. -9 ]
    gap> r[5];
    -4
    gap> r := [ 1, 4 .. 32 ];
    Error, Range: <high>-<low> must be divisible by <inc>
    gap> s := [];;  for i  in [10..20]  do Add( s, i^2 );  od;  s;
    [ 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400 ] 

The first section in this chapter describes the function that tests if a list is a range (see IsRange).

The other section tells you more about the internal representation of ranges (see More about Ranges).

Subsections

  1. IsRange
  2. More about Ranges
Previous Up Next
Index

GAP 3.4.4
April 1997