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 ].
[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.
last - first must be divisible by the increment
- 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
second-first to the entry
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; 12 gap> 17 in r; true gap> r := 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; 7 gap> r := [0,-1..-9]; [ 0, -1 .. -9 ] gap> r; -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).