CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download

GAP 4.8.9 installation with standard packages -- copy to your CoCalc project to get it

Path: gap4r8 / doc / tut / lists.xml
Views: 418346
1
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
2
<!-- %% -->
3
<!-- %W lists.tex GAP documentation Thomas Breuer -->
4
<!-- %W & Frank Celler -->
5
<!-- %W & Martin Schönert -->
6
<!-- %W & Heiko Theißen -->
7
<!-- %% -->
8
<!-- %H @(#)<M>Id: lists.tex,v 4.34 2002/10/04 12:04:17 gap Exp </M> -->
9
<!-- %% -->
10
<!-- %Y Copyright 1997, Lehrstuhl D für Mathematik, RWTH Aachen, Germany -->
11
<!-- %% -->
12
<!-- %% This file contains a tutorial introduction to lists and records. -->
13
<!-- %% -->
14
<P/>
15
16
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
17
<Chapter Label="Lists and Records">
18
<Heading>Lists and Records</Heading>
19
20
<Index>arrays, see lists</Index>
21
Modern mathematics, especially algebra, is based on set theory. When sets
22
are represented in a computer, they inadvertently turn into lists. That's
23
why we start our survey of the various objects &GAP; can handle with a
24
description of lists and their manipulation. &GAP; regards sets as a
25
special kind of lists, namely as lists without holes or duplicates whose
26
entries are ordered with respect to the precedence relation&nbsp;<C>&lt;</C>.
27
<P/>
28
After the introduction of the basic manipulations with lists
29
in&nbsp;<Ref Sect="Plain Lists"/>,
30
some difficulties concerning identity and mutability of lists are
31
discussed in&nbsp;<Ref Sect="Identical Lists"/>
32
and&nbsp;<Ref Sect="Immutability"/>.
33
Sets, ranges, row vectors, and matrices are introduced as special kinds
34
of lists in&nbsp;<Ref Sect="Sets"/>, <Ref Sect="Ranges"/>,
35
<Ref Sect="Vectors and Matrices"/>.
36
Handy list operations are shown in&nbsp;<Ref Sect="List Operations"/>.
37
Finally we explain how to use records in&nbsp;<Ref Sect="Plain Records"/>.
38
39
40
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
41
<Section Label="Plain Lists">
42
<Heading>Plain Lists</Heading>
43
44
<Index Subkey="plain">lists</Index>
45
A <E>list</E> is a collection of objects separated by commas and enclosed in
46
brackets. Let us for example construct the list <C>primes</C> of the first
47
ten prime numbers.
48
<P/>
49
<Example><![CDATA[
50
gap> primes:= [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
51
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
52
]]></Example>
53
<P/>
54
The next two primes are 31 and 37. They may be appended to the existing
55
list by the function <C>Append</C> which takes the existing list as its first
56
and another list as a second argument. The second argument is appended
57
to the list <C>primes</C> and no value is returned. Note that by appending
58
another list the object <C>primes</C> is changed.
59
<P/>
60
<Example><![CDATA[
61
gap> Append(primes, [31, 37]);
62
gap> primes;
63
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 ]
64
]]></Example>
65
<P/>
66
You can as well add single new elements to existing lists by the function
67
<C>Add</C> which takes the existing list as its first argument and a new
68
element as its second argument. The new element is added to the list
69
<C>primes</C> and again no value is returned but the list <C>primes</C> is changed.
70
<P/>
71
<Example><![CDATA[
72
gap> Add(primes, 41);
73
gap> primes;
74
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41 ]
75
]]></Example>
76
<P/>
77
Single elements of a list are referred to by their position in the list.
78
To get the value of the seventh prime, that is the seventh entry in our
79
list <C>primes</C>, you simply type
80
<P/>
81
<Example><![CDATA[
82
gap> primes[7];
83
17
84
]]></Example>
85
<P/>
86
This value can be handled like any other value, for example multiplied by 2
87
or assigned to a variable. On the other hand this mechanism allows one to
88
assign a value to a position in a list. So the next prime 43 may be
89
inserted in the list directly after the last occupied position of
90
<C>primes</C>. This last occupied position is returned by the function
91
<C>Length</C>.
92
<P/>
93
<Example><![CDATA[
94
gap> Length(primes);
95
13
96
gap> primes[14]:= 43;
97
43
98
gap> primes;
99
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 ]
100
]]></Example>
101
<P/>
102
Note that this operation again has changed the object <C>primes</C>. The
103
next position after the end of a list is not the only position capable
104
of taking a new value. If you know that 71 is the 20th prime, you can
105
enter it right now in the 20th position of <C>primes</C>. This will result
106
in a list with holes which is however still a list and now has length
107
20.
108
<P/>
109
<Example><![CDATA[
110
gap> primes[20]:= 71;
111
71
112
gap> primes;
113
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,,,,,, 71 ]
114
gap> Length(primes);
115
20
116
]]></Example>
117
<P/>
118
The list itself however must exist before a value can be assigned to a
119
position of the list. This list may be the empty list <C>[ ]</C>.
120
<P/>
121
<Log><![CDATA[
122
gap> lll[1]:= 2;
123
Error, Variable: 'lll' must have a value
124
125
126
gap> lll:= []; lll[1]:= 2;
127
[ ]
128
2
129
]]></Log>
130
<P/>
131
Of course existing entries of a list can be changed by this mechanism,
132
too. We will not do it here because <C>primes</C> then may no longer be a list
133
of primes. Try for yourself to change the 17 in the list into a 9.
134
<P/>
135
To get the position of 17 in the list <C>primes</C> use the function
136
<Ref Func="Position" BookName="ref"/> which takes the list as its
137
first argument and the element as
138
its second argument and returns the position of the first occurrence of
139
the element 17 in the list <C>primes</C>.
140
If the element is not contained in the list then
141
<Ref Func="Position" BookName="ref"/> will return the special object
142
<K>fail</K>.
143
<P/>
144
<Example><![CDATA[
145
gap> Position(primes, 17);
146
7
147
gap> Position(primes, 20);
148
fail
149
]]></Example>
150
<P/>
151
In all of the above changes to the list <C>primes</C>, the list has been
152
automatically resized. There is no need for you to tell &GAP; how big
153
you want a list to be. This is all done dynamically.
154
<P/>
155
It is not necessary for the objects collected in a list to be of the same
156
type.
157
<P/>
158
<Example><![CDATA[
159
gap> lll:= [true, "This is a String",,, 3];
160
[ true, "This is a String",,, 3 ]
161
]]></Example>
162
<P/>
163
In the same way a list may be part of another list.
164
<P/>
165
<Example><![CDATA[
166
gap> lll[3]:= [4,5,6];; lll;
167
[ true, "This is a String", [ 4, 5, 6 ],, 3 ]
168
]]></Example>
169
<P/>
170
A list may even be part of itself.
171
<P/>
172
<Log><![CDATA[
173
gap> lll[4]:= lll;
174
[ true, "This is a String", [ 4, 5, 6 ], ~, 3 ]
175
]]></Log>
176
<P/>
177
Now the tilde in the fourth position of <C>lll</C> denotes the object that is
178
currently printed. Note that the result of the last operation is the
179
actual value of the object <C>lll</C> on the right hand side of the
180
assignment. In fact it is identical to the value of the whole list
181
<C>lll</C> on the left hand side of the assignment.
182
<P/>
183
<Index>strings</Index>
184
<Index Subkey="dense">lists</Index>
185
A <E>string</E> is a special type of list,
186
namely a dense list of <E>characters</E>, where <E>dense</E> means that the list has
187
no holes. Here, <E>characters</E> are special &GAP; objects representing an
188
element of the character set of the operating system. The input of printable
189
characters is by enclosing them in single quotes&nbsp;<C>'</C>. A string literal
190
can either be entered as the list of characters or by writing the characters
191
between doublequotes <C>"</C>. Strings are handled specially by
192
<Ref Func="Print" BookName="ref"/>.
193
You can learn much more about strings in the reference manual.
194
<P/>
195
<Example><![CDATA[
196
gap> s1 := ['H','a','l','l','o',' ','w','o','r','l','d','.'];
197
"Hallo world."
198
gap> s1 = "Hallo world.";
199
true
200
gap> s1[7];
201
'w'
202
]]></Example>
203
<P/>
204
Sublists of lists can easily be extracted and assigned using the operator
205
<C><A>list</A>{ <A>positions</A> }</C>.
206
<P/>
207
<Example><![CDATA[
208
gap> sl := lll{ [ 1, 2, 3 ] };
209
[ true, "This is a String", [ 4, 5, 6 ] ]
210
gap> sl{ [ 2, 3 ] } := [ "New String", false ];
211
[ "New String", false ]
212
gap> sl;
213
[ true, "New String", false ]
214
]]></Example>
215
<P/>
216
This way you get a new list whose <M>i</M>-th entry is that element of the
217
original list whose position is the <M>i</M>-th entry of the argument in the
218
curly braces.
219
220
</Section>
221
222
223
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
224
<Section Label="Identical Lists">
225
<Heading>Identical Lists</Heading>
226
227
<Index Subkey="identical">lists</Index>
228
This second section about lists is dedicated to the subtle difference
229
between <E>equality</E> and <E>identity</E> of lists. It is really important to
230
understand this difference in order to understand how complex data
231
structures are realized in &GAP;. This section applies to all &GAP;
232
objects that have subobjects, e.g., to lists and to records. After
233
reading the section&nbsp;<Ref Sect="Plain Records"/> about records you should return to
234
this section and translate it into the record context.
235
<P/>
236
Two lists are <E>equal</E> if all their entries are equal. This means that the
237
equality operator <C>=</C> returns <K>true</K> for the comparison of two lists if
238
and only if these two lists are of the same length and for each position
239
the values in the respective lists are equal.
240
<P/>
241
<Example><![CDATA[
242
gap> numbers := primes;; numbers = primes;
243
true
244
]]></Example>
245
<P/>
246
We assigned the list <C>primes</C> to the variable <C>numbers</C> and, of course
247
they are equal as they have both the same length and the same entries.
248
Now we will change the third number to 4 and compare the result again
249
with <C>primes</C>.
250
<P/>
251
<Example><![CDATA[
252
gap> numbers[3]:= 4;; numbers = primes;
253
true
254
]]></Example>
255
<P/>
256
You see that <C>numbers</C> and <C>primes</C> are still equal, check this by
257
printing the value of <C>primes</C>. The list <C>primes</C> is no longer a list of
258
primes! What has happened? The truth is that the lists <C>primes</C> and
259
<C>numbers</C> are not only equal but they are also <E>identical</E>. <C>primes</C> and
260
<C>numbers</C> are two variables pointing to the same list. If you change the
261
value of the subobject <C>numbers[3]</C> of <C>numbers</C> this will also change
262
<C>primes</C>. Variables do <E>not</E> point to a certain block of storage memory
263
but they do point to an object that occupies storage memory. So the
264
assignment <C>numbers := primes</C> did <E>not</E> create a new list in a different
265
place of memory but only created the new name <C>numbers</C> for the same old
266
list of primes.
267
<P/>
268
From this we see that <E>the same object can have several names.</E>
269
<P/>
270
If you want to change a list with the contents of <C>primes</C> independently
271
from <C>primes</C> you will have to make a copy of <C>primes</C> by the function
272
<C>ShallowCopy</C> which takes an object as its argument and returns a copy of
273
the argument. (We will first restore the old value of <C>primes</C>.)
274
<P/>
275
<Example><![CDATA[
276
gap> primes[3]:= 5;; primes;
277
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,,,,,, 71 ]
278
gap> numbers:= ShallowCopy(primes);; numbers = primes;
279
true
280
gap> numbers[3]:= 4;; numbers = primes;
281
false
282
]]></Example>
283
<P/>
284
Now <C>numbers</C> is no longer equal to <C>primes</C> and <C>primes</C> still is a list
285
of primes. Check this by printing the values of <C>numbers</C> and <C>primes</C>.
286
<P/>
287
Lists and records can be changed this way because &GAP; objects of these
288
types have subobjects.
289
To clarify this statement consider the following assignments.
290
<P/>
291
<Example><![CDATA[
292
gap> i:= 1;; j:= i;; i:= i+1;;
293
]]></Example>
294
<P/>
295
By adding 1 to <C>i</C> the value of <C>i</C> has changed. What happens to <C>j</C>?
296
After the second statement <C>j</C> points to the same object as <C>i</C>, namely
297
to the integer 1. The addition does <E>not</E> change the object <C>1</C> but
298
creates a new object according to the instruction <C>i+1</C>. It is actually
299
the assignment that changes the value of <C>i</C>. Therefore <C>j</C> still points
300
to the object <C>1</C>. Integers (like permutations and booleans) have no
301
subobjects. Objects of these types cannot be changed but can only be
302
replaced by other objects. And a replacement does not change the values
303
of other variables. In the above example an assignment of a new value to
304
the variable <C>numbers</C> would also not change the value of <C>primes</C>.
305
<P/>
306
Finally try the following examples and explain the results.
307
<P/>
308
<Log><![CDATA[
309
gap> l:= [];; l:= [l];
310
[ [ ] ]
311
gap> l[1]:= l;
312
[ ~ ]
313
]]></Log>
314
<P/>
315
Now return to Section&nbsp;<Ref Sect="Plain Lists"/> and find out whether
316
the functions <Ref Func="Add" BookName="ref"/> and
317
<Ref Func="Append" BookName="ref"/> change their arguments.
318
319
</Section>
320
321
322
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
323
<Section Label="Immutability">
324
<Heading>Immutability</Heading>
325
326
&GAP; has a mechanism that protects lists against changes like the ones
327
that have bothered us in Section&nbsp;<Ref Sect="Identical Lists"/>.
328
The function <Ref Func="Immutable" BookName="ref"/> takes as argument a list
329
and returns an immutable copy of it,
330
i.e., a list which looks exactly like the old one, but has two extra
331
properties:
332
(1)&nbsp;The new list is immutable, i.e., the list itself and its subobjects
333
cannot be changed.
334
(2)&nbsp;In constructing the copy, every part of the list that can be changed
335
has been copied, so that changes to the old list will not affect the
336
new one. In other words, the new list has no mutable subobjects in
337
common with the old list.
338
<P/>
339
<Log><![CDATA[
340
gap> list := [ 1, 2, "three", [ 4 ] ];; copy := Immutable( list );;
341
gap> list[3][5] := 'w';; list; copy;
342
[ 1, 2, "threw", [ 4 ] ]
343
[ 1, 2, "three", [ 4 ] ]
344
gap> copy[3][5] := 'w';
345
Lists Assignment: <list> must be a mutable list
346
not in any function
347
Entering break read-eval-print loop ...
348
you can 'quit;' to quit to outer loop, or
349
you can 'return;' and ignore the assignment to continue
350
brk> quit;
351
]]></Log>
352
<P/>
353
As a consequence of these rules, in the immutable copy of a list which
354
contains an already immutable list as subobject, this immutable subobject
355
need not be copied, because it is unchangeable. Immutable lists are
356
useful in many complex &GAP; objects, for example as generator lists of
357
groups. By making them immutable, &GAP; ensures that no generators can
358
be added to the list, removed or exchanged. Such changes would of course
359
lead to serious inconsistencies with other knowledge that may already
360
have been calculated for the group.
361
<P/>
362
A converse function to <Ref Func="Immutable" BookName="ref"/> is
363
<Ref Func="ShallowCopy" BookName="ref"/>, which produces a
364
new mutable list whose <M>i</M>-th entry is the <M>i</M>-th entry of the old
365
list. The single entries are not copied, they are just placed in the
366
new list. If the old list is immutable, and hence the list entries
367
are immutable themselves,
368
the result of <Ref Func="ShallowCopy" BookName="ref"/> is mutable only
369
on the top level.
370
<P/>
371
It should be noted that also other objects than lists can appear in
372
mutable or immutable form.
373
Records (see Section&nbsp;<Ref Sect="Plain Records"/>) provide another example.
374
375
</Section>
376
377
378
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
379
<Section Label="Sets">
380
<Heading>Sets</Heading>
381
382
<Index Subkey="strictly sorted">lists</Index>
383
<Index>family</Index>
384
&GAP; knows several special kinds of lists. A <E>set</E> in &GAP; is a
385
list that contains no holes (such a list is called <E>dense</E>) and whose
386
elements are strictly sorted w.r.t.&nbsp;<C>&lt;</C>; in particular, a set cannot
387
contain duplicates. (More precisely, the elements of a set in &GAP;
388
are required to lie in the same <E>family</E>, but roughly this means that
389
they can be compared using the <C>&lt;</C> operator.)
390
<P/>
391
This provides a natural model for mathematical sets whose elements are
392
given by an explicit enumeration.
393
<P/>
394
&GAP; also calls a set a <E>strictly sorted list</E>,
395
and the function <Ref Func="IsSSortedList" BookName="ref"/> tests
396
whether a given list is a set. It returns a
397
boolean value. For almost any list whose elements are contained in
398
the same family, there exists a corresponding set. This set is
399
constructed by the function <Ref Func="Set" BookName="ref"/>
400
which takes the list as its argument
401
and returns a set obtained from this list by ignoring holes and
402
duplicates and by sorting the elements.
403
<P/>
404
The elements of the sets used in the examples of this section are
405
strings.
406
<P/>
407
<Example><![CDATA[
408
gap> fruits:= ["apple", "strawberry", "cherry", "plum"];
409
[ "apple", "strawberry", "cherry", "plum" ]
410
gap> IsSSortedList(fruits);
411
false
412
gap> fruits:= Set(fruits);
413
[ "apple", "cherry", "plum", "strawberry" ]
414
]]></Example>
415
<P/>
416
Note that the original list <C>fruits</C> is not changed by the function
417
<Ref Func="Set" BookName="ref"/>.
418
We have to make a new assignment to the variable <C>fruits</C> in
419
order to make it a set.
420
<P/>
421
The operator <K>in</K> is used to test whether an object is an element of a
422
set. It returns a boolean value <K>true</K> or <K>false</K>.
423
<P/>
424
<Example><![CDATA[
425
gap> "apple" in fruits;
426
true
427
gap> "banana" in fruits;
428
false
429
]]></Example>
430
<P/>
431
The operator <K>in</K> can also be applied to ordinary lists. It is however
432
much faster to perform a membership test for sets since sets are
433
always sorted and a binary search can be used instead of a linear
434
search. New elements may be added to a set by the function
435
<Ref Func="AddSet" BookName="ref"/>
436
which takes the set <C>fruits</C> as its first argument and an element as
437
its second argument and adds the element to the set if it wasn't
438
already there. Note that the object <C>fruits</C> is changed.
439
<P/>
440
<Example><![CDATA[
441
gap> AddSet(fruits, "banana");
442
gap> fruits; # The banana is inserted in the right place.
443
[ "apple", "banana", "cherry", "plum", "strawberry" ]
444
gap> AddSet(fruits, "apple");
445
gap> fruits; # fruits has not changed.
446
[ "apple", "banana", "cherry", "plum", "strawberry" ]
447
]]></Example>
448
<P/>
449
Note that inserting new elements into a set with
450
<Ref Func="AddSet" BookName="ref"/> is usually more
451
expensive than simply adding new elements at the end of a list.
452
<P/>
453
Sets can be intersected by the function
454
<Ref Func="Intersection" BookName="ref"/> and united by the
455
function <Ref Func="Union" BookName="ref"/> which both take two sets
456
as their arguments and return
457
the intersection resp. union of the two sets as a new object.
458
<P/>
459
<Example><![CDATA[
460
gap> breakfast:= ["tea", "apple", "egg"];
461
[ "tea", "apple", "egg" ]
462
gap> Intersection(breakfast, fruits);
463
[ "apple" ]
464
]]></Example>
465
<P/>
466
The arguments of the functions <Ref Func="Intersection" BookName="ref"/>
467
and <Ref Func="Union" BookName="ref"/> could be
468
ordinary lists, while their result is always a set. Note that in the
469
preceding example at least one argument of
470
<Ref Func="Intersection" BookName="ref"/> was not a set.
471
The functions <Ref Func="IntersectSet" BookName="ref"/> and
472
<Ref Func="UniteSet" BookName="ref"/> also form the
473
intersection resp.&nbsp;union of two sets. They will however not return the
474
result but change their first argument to be the result. Try them
475
carefully.
476
477
</Section>
478
479
480
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
481
<Section Label="Ranges">
482
<Heading>Ranges</Heading>
483
484
A <E>range</E> is a finite arithmetic progression of integers. This is another
485
special kind of list. A range is described by the first two values and the last
486
value of the arithmetic progression which are given in the form
487
<C>[<A>first</A>,<A>second</A>..<A>last</A>]</C>.
488
In the usual case of an ascending list of
489
consecutive integers the second entry may be omitted.
490
<P/>
491
<Example><![CDATA[
492
gap> [1..999999]; # a range of almost a million numbers
493
[ 1 .. 999999 ]
494
gap> [1, 2..999999]; # this is equivalent
495
[ 1 .. 999999 ]
496
gap> [1, 3..999999]; # here the step is 2
497
[ 1, 3 .. 999999 ]
498
gap> Length( last );
499
500000
500
gap> [ 999999, 999997 .. 1 ];
501
[ 999999, 999997 .. 1 ]
502
]]></Example>
503
<P/>
504
This compact printed representation of a fairly long list corresponds to
505
a compact internal representation.
506
The function <Ref Func="IsRange" BookName="ref"/> tests
507
whether an object is a range,
508
the function <Ref Func="ConvertToRangeRep" BookName="ref"/> changes
509
the representation of a list
510
that is in fact a range to this compact internal representation.
511
<P/>
512
<Example><![CDATA[
513
gap> a:= [-2,-1,0,1,2,3,4,5];
514
[ -2, -1, 0, 1, 2, 3, 4, 5 ]
515
gap> IsRange( a );
516
true
517
gap> ConvertToRangeRep( a );; a;
518
[ -2 .. 5 ]
519
gap> a[1]:= 0;; IsRange( a );
520
false
521
]]></Example>
522
<P/>
523
Note that this change of representation does <E>not</E> change the value of
524
the list <C>a</C>. The list <C>a</C> still behaves in any context in the same way
525
as it would have in the long representation.
526
527
</Section>
528
529
530
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
531
<Section Label="For and While Loops">
532
<Heading>For and While Loops</Heading>
533
534
<Index Key="loops" Subkey="for">loop</Index>
535
<Index Key="loops" Subkey="while">loop</Index>
536
<P/>
537
Given a list <C>pp</C> of permutations we can form their product by means of a
538
<K>for</K> loop instead of writing down the product explicitly.
539
<P/>
540
<Example><![CDATA[
541
gap> pp:= [ (1,3,2,6,8)(4,5,9), (1,6)(2,7,8), (1,5,7)(2,3,8,6),
542
> (1,8,9)(2,3,5,6,4), (1,9,8,6,3,4,7,2)];;
543
gap> prod:= ();
544
()
545
gap> for p in pp do
546
> prod:= prod*p;
547
> od;
548
gap> prod;
549
(1,8,4,2,3,6,5,9)
550
]]></Example>
551
<P/>
552
First a new variable <C>prod</C> is initialized to the identity permutation
553
<C>()</C>. Then the loop variable <C>p</C> takes as its value one permutation after
554
the other from the list <C>pp</C> and is multiplied with the present value of
555
<C>prod</C> resulting in a new value which is then assigned to <C>prod</C>.
556
<P/>
557
The <K>for</K> loop has the following syntax
558
<P/>
559
<K>for</K> <A>var</A> <K>in</K> <A>list</A> <K>do</K> <A>statements</A> <K>od</K><C>;</C>
560
<P/>
561
The effect of the <K>for</K> loop is to execute the <A>statements</A> for every
562
element of the <A>list</A>. A <K>for</K> loop is a statement and therefore
563
terminated by a semicolon. The list of <A>statements</A> is enclosed by the
564
keywords <K>do</K> and <K>od</K> (reverse <K>do</K>). A <K>for</K> loop returns no value.
565
Therefore we had to ask explicitly for the value of <C>prod</C> in the
566
preceding example.
567
<P/>
568
The <K>for</K> loop can loop over any kind of list, even a list with holes.
569
In many programming languages the <K>for</K> loop has the form
570
<P/>
571
<C>for <A>var</A> from <A>first</A> to <A>last</A> do <A>statements</A> od;</C>
572
<P/>
573
In &GAP; this is merely a special case of the general <K>for</K> loop as defined
574
above where the <A>list</A> in the loop body is a range (see&nbsp;<Ref Sect="Ranges"/>):
575
<P/>
576
<K>for</K> <A>var</A> <K>in</K> <C>[<A>first</A>..<A>last</A>]</C> <K>do</K> <A>statements</A> <K>od</K><C>;</C>
577
<P/>
578
You can for instance loop over a range to compute the factorial <M>15!</M>
579
of the number <M>15</M> in the following way.
580
<P/>
581
<Example><![CDATA[
582
gap> ff:= 1;
583
1
584
gap> for i in [1..15] do
585
> ff:= ff * i;
586
> od;
587
gap> ff;
588
1307674368000
589
]]></Example>
590
<P/>
591
The <K>while</K> loop has the following syntax
592
<P/>
593
<K>while</K> <A>condition</A> <K>do</K> <A>statements</A> <K>od</K><C>;</C>
594
<P/>
595
The <K>while</K> loop loops over the <A>statements</A> as long as the
596
<A>condition</A> evaluates to <K>true</K>. Like the <K>for</K> loop the <K>while</K> loop
597
is terminated by the keyword <K>od</K> followed by a semicolon.
598
<P/>
599
We can use our list <C>primes</C> to perform a very simple factorization. We
600
begin by initializing a list <C>factors</C> to the empty list. In this list
601
we want to collect the prime factors of the number 1333. Remember that a
602
list has to exist before any values can be assigned to positions of the
603
list. Then we will loop over the list <C>primes</C> and test for each prime
604
whether it divides the number. If it does we will divide the number by
605
that prime, add it to the list <C>factors</C> and continue.
606
<P/>
607
<Example><![CDATA[
608
gap> n:= 1333;;
609
gap> factors:= [];;
610
gap> for p in primes do
611
> while n mod p = 0 do
612
> n:= n/p;
613
> Add(factors, p);
614
> od;
615
> od;
616
gap> factors;
617
[ 31, 43 ]
618
gap> n;
619
1
620
]]></Example>
621
<P/>
622
As <C>n</C> now has the value 1 all prime factors of 1333 have been found and
623
<C>factors</C> contains a complete factorization of 1333. This can of course
624
be verified by multiplying 31 and 43.
625
<P/>
626
This loop may be applied to arbitrary numbers in order to find prime
627
factors. But as <C>primes</C> is not a complete list of all primes this loop
628
may fail to find all prime factors of a number greater than 2000, say.
629
You can try to improve it in such a way that new primes are added to the
630
list <C>primes</C> if needed.
631
<P/>
632
You have already seen that list objects may be changed. This of
633
course also holds for the list in a loop body. In most cases you have to be
634
careful not to change this list, but there are situations where this is
635
quite useful. The following example shows a quick way to determine the
636
primes smaller than 1000 by a sieve method. Here we will make use of the
637
function <C>Unbind</C> to delete entries from a list, and the <C>if</C>
638
statement covered in <Ref Sect="If Statements"/>.
639
<P/>
640
<Example><![CDATA[
641
gap> primes:= [];;
642
gap> numbers:= [2..1000];;
643
gap> for p in numbers do
644
> Add(primes, p);
645
> for n in numbers do
646
> if n mod p = 0 then
647
> Unbind(numbers[n-1]);
648
> fi;
649
> od;
650
> od;
651
]]></Example>
652
<P/>
653
The inner loop removes all entries from <C>numbers</C> that are divisible by
654
the last detected prime <C>p</C>. This is done by the function <C>Unbind</C> which
655
deletes the binding of the list position <C>numbers[n-1]</C> to the value <C>n</C>
656
so that afterwards <C>numbers[n-1]</C> no longer has an assigned value. The
657
next element encountered in <C>numbers</C> by the outer loop necessarily is
658
the next prime.
659
<P/>
660
In a similar way it is possible to enlarge the list which is looped over.
661
This yields a nice and short orbit algorithm for the action of a group,
662
for example.
663
<P/>
664
More about <K>for</K> and <K>while</K> loops can be found in the
665
sections&nbsp;<Ref Sect="While" BookName="ref"/> and&nbsp;<Ref Sect="For" BookName="ref"/>.
666
667
</Section>
668
669
670
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
671
<Section Label="List Operations">
672
<Heading>List Operations</Heading>
673
674
There is a more comfortable way than that given in the previous section to
675
compute the product of a list of numbers or permutations.
676
<P/>
677
<Example><![CDATA[
678
gap> Product([1..15]);
679
1307674368000
680
gap> Product(pp);
681
(1,8,4,2,3,6,5,9)
682
]]></Example>
683
<P/>
684
The function <Ref Func="Product" BookName="ref"/> takes a list
685
as its argument and computes the
686
product of the elements of the list. This is possible whenever a
687
multiplication of the elements of the list is defined.
688
So <Ref Func="Product" BookName="ref"/>
689
executes a loop over all elements of the list.
690
<P/>
691
There are other often used loops available as functions.
692
Guess what the function <Ref Func="Sum" BookName="ref"/> does.
693
The function <Ref Func="List" BookName="ref"/> may take a list and a function
694
as its arguments. It will then apply the function to each element of the
695
list and return the corresponding list of results. A list of cubes is
696
produced as follows with the function <C>cubed</C> from
697
Section&nbsp;<Ref Chap="Functions"/>.
698
<P/>
699
<Example><![CDATA[
700
gap> cubed:= x -> x^3;;
701
gap> List([2..10], cubed);
702
[ 8, 27, 64, 125, 216, 343, 512, 729, 1000 ]
703
]]></Example>
704
<P/>
705
To add all these cubes we might apply the function
706
<Ref Func="Sum" BookName="ref"/> to the last list.
707
But we may as well give the function <C>cubed</C> to
708
<Ref Func="Sum" BookName="ref"/> as an additional argument.
709
<P/>
710
<Example><![CDATA[
711
gap> Sum(last) = Sum([2..10], cubed);
712
true
713
]]></Example>
714
<P/>
715
The primes less than 30 can be retrieved out of the list <C>primes</C> from
716
Section&nbsp;<Ref Sect="Plain Lists"/> by the function
717
<Ref Func="Filtered" BookName="ref"/>. This function takes the
718
list <C>primes</C> and a property as its arguments and will return the list of
719
those elements of <C>primes</C> which have this property. Such a property will
720
be represented by a function that returns a boolean value. In this
721
example the property of being less than 30 can be represented by the
722
function <C>x -> x &lt; 30</C> since <C>x &lt; 30</C> will evaluate to <K>true</K> for
723
values <C>x</C> less than 30 and to <K>false</K> otherwise.
724
<P/>
725
<Example><![CDATA[
726
gap> Filtered(primes, x -> x < 30);
727
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
728
]]></Example>
729
<P/>
730
We have already mentioned the operator <C>{ }</C> that forms sublists. It
731
takes a list of positions as its argument and will return the list of
732
elements from the original list corresponding to these positions.
733
<P/>
734
<Example><![CDATA[
735
gap> primes{ [1 .. 10] };
736
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
737
]]></Example>
738
<P/>
739
Finally we mention the function <Ref Func="ForAll" BookName="ref"/>
740
that checks whether a property
741
holds for all elements of a list. It takes as its arguments a list and a
742
function that returns a boolean value.
743
<Ref Func="ForAll" BookName="ref"/> checks whether the
744
function returns <K>true</K> for all elements of the list.
745
<P/>
746
<Example><![CDATA[
747
gap> list:= [ 1, 2, 3, 4 ];;
748
gap> ForAll( list, x -> x > 0 );
749
true
750
gap> ForAll( list, x -> x in primes );
751
false
752
]]></Example>
753
<P/>
754
You will find more predefined <K>for</K> loops in
755
chapter&nbsp;<Ref Chap="Lists" BookName="ref"/>.
756
757
</Section>
758
759
760
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
761
<Section Label="Vectors and Matrices">
762
<Heading>Vectors and Matrices</Heading>
763
764
<Index Subkey="row">vectors</Index>
765
<Index>matrices</Index>
766
This section describes how &GAP; uses lists to represent row vectors and
767
matrices. A <E>row vector</E> is a dense list of elements from a common field.
768
A <E>matrix</E> is a dense list of row vectors over a common field and of
769
equal length.
770
<P/>
771
<Example><![CDATA[
772
gap> v:= [3, 6, 2, 5/2];; IsRowVector(v);
773
true
774
]]></Example>
775
<P/>
776
Row vectors may be added and multiplied by scalars from their field.
777
Multiplication of row vectors of equal length results in their scalar
778
product.
779
<P/>
780
<Example><![CDATA[
781
gap> 2 * v; v * 1/3;
782
[ 6, 12, 4, 5 ]
783
[ 1, 2, 2/3, 5/6 ]
784
gap> v * v; # the scalar product of `v' with itself
785
221/4
786
]]></Example>
787
<P/>
788
Note that the expression <C>v * 1/3</C> is actually evaluated by first
789
multiplying <C>v</C> by 1 (which yields again <C>v</C>) and by then dividing by 3.
790
This is also an allowed scalar operation. The expression <C>v/3</C> would
791
result in the same value.
792
<P/>
793
Such arithmetical operations (if the results are again vectors)
794
result in <E>mutable</E> vectors except if the operation is binary
795
and both operands are immutable;
796
thus the vectors shown in the examples above are all mutable.
797
<P/>
798
So if you want to produce a mutable list with 100&nbsp;entries equal to&nbsp;25,
799
you can simply say <C>25 + 0 * [ 1 .. 100 ]</C>.
800
Note that ranges are also vectors (over the rationals),
801
and that <C>[ 1 .. 100 ]</C> is mutable.
802
<P/>
803
A matrix is a dense list of row vectors of equal length.
804
<P/>
805
<Example><![CDATA[
806
gap> m:= [[1,-1, 1],
807
> [2, 0,-1],
808
> [1, 1, 1]];
809
[ [ 1, -1, 1 ], [ 2, 0, -1 ], [ 1, 1, 1 ] ]
810
gap> m[2][1];
811
2
812
]]></Example>
813
<P/>
814
Syntactically a matrix is a list of lists. So the number 2 in the second
815
row and the first column of the matrix <C>m</C> is referred to as the first
816
element of the second element of the list <C>m</C> via <C>m[2][1]</C>.
817
<P/>
818
A matrix may be multiplied by scalars, row vectors and other matrices.
819
(If the row vectors and matrices involved in such a multiplication do not
820
have suitable dimensions then the <Q>missing</Q> entries are treated as zeros,
821
so the results may look unexpectedly in such cases.)
822
<P/>
823
<Example><![CDATA[
824
gap> [1, 0, 0] * m;
825
[ 1, -1, 1 ]
826
gap> [1, 0, 0, 2] * m;
827
[ 1, -1, 1 ]
828
gap> m * [1, 0, 0];
829
[ 1, 2, 1 ]
830
gap> m * [1, 0, 0, 2];
831
[ 1, 2, 1 ]
832
]]></Example>
833
<P/>
834
Note that multiplication of a row vector with a matrix will result in a
835
linear combination of the rows of the matrix, while multiplication of a
836
matrix with a row vector results in a linear combination of the columns
837
of the matrix. In the latter case the row vector is considered as a
838
column vector.
839
<P/>
840
A vector or matrix of integers can also be multiplied
841
with a finite field scalar and vice versa.
842
Such products result in a matrix over the finite field with the integers
843
mapped into the finite field in the obvious way.
844
Finite field matrices are nicer to read when they are <C>Display</C>ed rather
845
than <C>Print</C>ed.
846
(Here we write <C>Z(q)</C> to denote a primitive root of the finite field
847
with <C>q</C> elements.)
848
<P/>
849
<Example><![CDATA[
850
gap> Display( m * One( GF(5) ) );
851
1 4 1
852
2 . 4
853
1 1 1
854
gap> Display( m^2 * Z(2) + m * Z(4) );
855
z = Z(4)
856
z^1 z^1 z^2
857
1 1 z^2
858
z^1 z^1 z^2
859
]]></Example>
860
<P/>
861
Submatrices can easily be extracted using the expression
862
<C><A>mat</A>{<A>rows</A>}{<A>columns</A>}</C>. They can also be assigned to, provided
863
the big matrix is mutable (which it is not if it is the result of an
864
arithmetical operation, see above).
865
<P/>
866
<Example><![CDATA[
867
gap> sm := m{ [ 1, 2 ] }{ [ 2, 3 ] };
868
[ [ -1, 1 ], [ 0, -1 ] ]
869
gap> sm{ [ 1, 2 ] }{ [2] } := [[-2],[0]];; sm;
870
[ [ -1, -2 ], [ 0, 0 ] ]
871
]]></Example>
872
<P/>
873
The first curly brackets contain the selection of rows,
874
the second that of columns.
875
<P/>
876
Matrices appear not only in linear algebra, but also as group elements,
877
provided they are invertible.
878
Here we have the opportunity to meet a group-theoretical function,
879
namely <Ref Func="Order" BookName="ref"/>,
880
which computes the order of a group element.
881
<P/>
882
<Example><![CDATA[
883
gap> Order( m * One( GF(5) ) );
884
8
885
gap> Order( m );
886
infinity
887
]]></Example>
888
<P/>
889
For matrices whose entries are more complex objects, for example rational
890
functions, &GAP;'s <Ref Func="Order" BookName="ref"/> methods might not be
891
able to prove that the
892
matrix has infinite order, and one gets the following warning.
893
<Log><![CDATA[
894
#I Order: warning, order of <mat> might be infinite
895
]]></Log>
896
In such a case, if the order of the matrix really is infinite, you will
897
have to interrupt &GAP; by pressing <C><A>ctl</A>-C</C> (followed by <C><A>ctl</A>-D</C> or
898
<C>quit;</C> to leave the break loop).
899
<P/>
900
To prove that the order of <C>m</C> is infinite, we also could look at the
901
minimal polynomial of <C>m</C> over the rationals.
902
<P/>
903
<Example><![CDATA[
904
gap> f:= MinimalPolynomial( Rationals, m );; Factors( f );
905
[ x_1-2, x_1^2+3 ]
906
]]></Example>
907
<P/>
908
<Ref Func="Factors" BookName="ref"/> returns a list of irreducible factors
909
of the polynomial <C>f</C>.
910
The first irreducible factor <M>X-2</M> reveals that 2 is an eigenvalue of
911
<C>m</C>, hence its order cannot be finite.
912
913
</Section>
914
915
916
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
917
<Section Label="Plain Records">
918
<Heading>Plain Records</Heading>
919
920
A record provides another way to build new data structures. Like a list
921
a record contains subobjects.
922
In a record the elements, the so-called <E>record components</E>,
923
are not indexed by numbers but by names.
924
<P/>
925
In this section you will see how to define and how to use records.
926
Records are changed by assignments to record components
927
or by unbinding record components.
928
<P/>
929
Initially a record is defined as a comma separated list of assignments to
930
its record components.
931
<P/>
932
<Example><![CDATA[
933
gap> date:= rec(year:= 1997,
934
> month:= "Jul",
935
> day:= 14);
936
rec( day := 14, month := "Jul", year := 1997 )
937
]]></Example>
938
<P/>
939
The value of a record component is accessible by the record name and the
940
record component name separated by one dot as the record component
941
selector.
942
<P/>
943
<Example><![CDATA[
944
gap> date.year;
945
1997
946
]]></Example>
947
<P/>
948
Assignments to new record components are possible in the same way. The
949
record is automatically resized to hold the new component.
950
<P/>
951
<Example><![CDATA[
952
gap> date.time:= rec(hour:= 19, minute:= 23, second:= 12);
953
rec( hour := 19, minute := 23, second := 12 )
954
gap> date;
955
rec( day := 14, month := "Jul",
956
time := rec( hour := 19, minute := 23, second := 12 ), year := 1997 )
957
]]></Example>
958
<P/>
959
Records are objects that may be changed. An assignment to a record
960
component changes the original object.
961
The remarks made in Sections&nbsp;<Ref Sect="Identical Lists"/> and <Ref Sect="Immutability"/>
962
about identity and mutability of lists are also true for records.
963
<P/>
964
Sometimes it is interesting to know which components of a certain record
965
are bound. This information is available from the function
966
<Ref Func="RecNames" BookName="ref"/>,
967
which takes a record as its argument and returns a list of names of
968
all bound components of this record as a list of strings.
969
<P/>
970
<Example><![CDATA[
971
gap> RecNames(date);
972
[ "time", "year", "month", "day" ]
973
]]></Example>
974
<P/>
975
Now return to Sections <Ref Sect="Identical Lists"/> and <Ref Sect="Immutability"/> and find out
976
what these sections mean for records.
977
978
</Section>
979
980
981
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
982
<Section Label="Further Information about Lists">
983
<Heading>Further Information about Lists</Heading>
984
985
(The following cross-references point to the &GAP; Reference Manual.)
986
<P/>
987
<!-- % In this chapter you have encountered the fundamental concept of a list. -->
988
<!-- % You have seen how to construct lists, how to extend them and how to refer -->
989
<!-- % to single elements of a list. -->
990
<!-- % Moreover you have seen that lists may contain elements of different -->
991
<!-- % types, even holes (unbound entries), -->
992
<!-- % and that a list may be an entry of itself or of one of its entries. -->
993
<!-- % -->
994
<!-- % You have seen the difference between equal lists and identical lists. -->
995
<!-- % Since lists are objects that have subobjects, they can be mutable or -->
996
<!-- % immutable, and mutable lists can be changed. -->
997
<!-- % Changing an object will change the values of all variables that point to -->
998
<!-- % that object. -->
999
<!-- % Be careful, since one object can have several names. -->
1000
<!-- % The function <C>ShallowCopy</C> creates a shallow copy of a list which is then -->
1001
<!-- % a new object. -->
1002
<!-- % -->
1003
You will find more about lists, sets, and ranges in Chapter&nbsp;<Ref Chap="Lists" BookName="ref"/>,
1004
in particular more about identical lists in Section&nbsp;<Ref Sect="Identical Lists" BookName="ref"/>.
1005
<!-- % -->
1006
<!-- % You have seen that sets are a special kind of list. -->
1007
<!-- % There are functions to expand sets, intersect or unite sets, and there is -->
1008
<!-- % the membership test with the <C>in</C> operator. -->
1009
<!-- % Sets are described in more detail in Chapter&nbsp;<Ref Sect="Sets" BookName="ref"/>. -->
1010
<!-- % -->
1011
<!-- % You have seen that finite arithmetic progressions of integers can be -->
1012
<!-- % represented in a compact way as ranges. -->
1013
<!-- % Chapter&nbsp;<Ref Sect="Ranges" BookName="ref"/> contains a detailed description of ranges. -->
1014
<!-- % -->
1015
A more detailed description of strings is contained in
1016
Chapter&nbsp;<Ref Chap="Strings and Characters" BookName="ref"/>.
1017
<!-- % -->
1018
<!-- % You have met row vectors and matrices as special lists, -->
1019
<!-- % and you have seen how to refer to entries of a matrix and how to multiply -->
1020
<!-- % scalars, row vectors, and matrices. -->
1021
<!-- % -->
1022
Fields are described in Chapter&nbsp;<Ref Chap="Fields and Division Rings" BookName="ref"/>,
1023
some known fields in &GAP; are described in Chapters&nbsp;<Ref Chap="Rational Numbers" BookName="ref"/>,
1024
<Ref Chap="Abelian Number Fields" BookName="ref"/>,
1025
and&nbsp;<Ref Chap="Finite Fields" BookName="ref"/>.
1026
Row vectors and matrices are described in more detail in Chapters&nbsp;<Ref Chap="Row Vectors" BookName="ref"/>
1027
and&nbsp;<Ref Chap="Matrices" BookName="ref"/>.
1028
Vector spaces are described in Chapter&nbsp;<Ref Chap="Vector Spaces" BookName="ref"/>,
1029
further matrix related structures are described in Chapters&nbsp;<Ref Chap="Matrix Groups" BookName="ref"/>,
1030
<Ref Chap="Algebras" BookName="ref"/>,
1031
and&nbsp;<Ref Chap="Lie Algebras" BookName="ref"/>.
1032
<!-- % -->
1033
<!-- % You have learned how to loop over a list by the <K>for</K> loop and how to -->
1034
<!-- % loop with respect to a logical condition with the <K>while</K> loop. -->
1035
<!-- % You have seen that even the list in the loop body can be changed. -->
1036
<P/>
1037
<!-- % -->
1038
<!-- % You have seen some functions which implement often used <K>for</K> loops. -->
1039
<!-- % There are functions like <C>Product</C> to form the product of the elements of -->
1040
<!-- % a list. -->
1041
<!-- % The function <C>List</C> can apply a function to all elements of a list -->
1042
<!-- % and the function <C>Filtered</C> creates a sublist of a given list. -->
1043
You will find more list operations in Chapter&nbsp;<Ref Chap="Lists" BookName="ref"/>.
1044
<P/>
1045
Records and functions for records are described in detail
1046
in Chapter&nbsp;<Ref Chap="Records" BookName="ref"/>.
1047
1048
</Section>
1049
</Chapter>
1050
1051
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
1052
<!-- %% -->
1053
<!-- %E -->
1054
1055
1056