aboutsummaryrefslogtreecommitdiff
path: root/src/hyper/pages/ug05.ht
blob: 6d861686af2e125ab6f02549c4594f6422f9e515 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
% Copyright The Numerical Algorithms Group Limited 1992-94. All rights reserved.
% !! DO NOT MODIFY THIS FILE BY HAND !! Created by ht.awk.
\texht{\setcounter{chapter}{4}}{} % Chapter 5

%
\newcommand{\ugLangTitle}{Introduction to the \Language{} Interactive Language}
\newcommand{\ugLangNumber}{5.}
%
% =====================================================================
\begin{page}{ugLangPage}{5. Introduction to the \Language{} Interactive Language}
% =====================================================================
\beginscroll

In this chapter we look at some of the basic components of the
\Language{} language that you can use interactively.
We show how to create a \spadgloss{block} of expressions,
how to form loops and list iterations, how to modify the sequential
evaluation of a block and how to use {\tt if-then-else} to
evaluate parts of your program conditionally.
We suggest you first read the boxed material in each section and then
proceed to a more thorough reading of the chapter.

\beginmenu
    \menudownlink{{5.1. Immediate and Delayed Assignments}}{ugLangAssignPage}
    \menudownlink{{5.2. Blocks}}{ugLangBlocksPage}
    \menudownlink{{5.3. if-then-else}}{ugLangIfPage}
    \menudownlink{{5.4. Loops}}{ugLangLoopsPage}
    \menudownlink{{5.5. Creating Lists and Streams with Iterators}}{ugLangItsPage}
    \menudownlink{{5.6. An Example: Streams of Primes}}{ugLangStreamsPrimesPage}
\endmenu
\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangAssignTitle}{Immediate and Delayed Assignments}
\newcommand{\ugLangAssignNumber}{5.1.}
%
% =====================================================================
\begin{page}{ugLangAssignPage}{5.1. Immediate and Delayed Assignments}
% =====================================================================
\beginscroll

A \spadgloss{variable} in \Language{} refers to a value.
A variable has a name beginning with an uppercase or lowercase alphabetic
character, \axiomSyntax{\%}, or \axiomSyntax{!}.
Successive characters (if any) can be any of the above, digits, or
\axiomSyntax{?}.
Case is distinguished.
The following are all examples of valid, distinct variable names:
\begin{verbatim}
a             tooBig?    a1B2c3%!?
A             %j         numberOfPoints
beta6         %J         numberofpoints
\end{verbatim}

The \axiomSyntax{:=} operator is the immediate \spadgloss{assignment}
operator.
%-% \HDindex{assignment!immediate}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
Use it to associate a value with a variable.
%-% \HDindex{immediate assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}

\beginImportant
The syntax for immediate assignment for a single variable is
\centerline{{{\it variable} \axiom{:=} {\it expression}}}
The value returned by an immediate assignment is the value of {\it expression}.
\endImportant

\xtc{
The right-hand side of the expression is evaluated,
yielding \axiom{1}.  This value is then assigned to \axiom{a}.
}{
\spadpaste{a := 1 \bound{a}}
}
\xtc{
The right-hand side of the expression is evaluated,
yielding \axiom{1}.  This value is then assigned to \axiom{b}.
Thus \axiom{a} and \axiom{b} both have the value \axiom{1} after the sequence
of assignments.
}{
\spadpaste{b := a \free{a}\bound{b}}
}
\xtc{
What is the value of \axiom{b} if \axiom{a} is
assigned the value \axiom{2}?
}{
\spadpaste{a := 2 \bound{a2}}
}
\xtc{
As you see, the value of \axiom{b} is left unchanged.
}{
\spadpaste{b \free{b}}
}
This is what we mean when we say this kind of assignment is
{\it immediate};
\axiom{b} has no dependency on \axiom{a} after the initial assignment.
This is the usual notion of assignment found in programming
languages such as C,
%-% \HDindex{C language!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
PASCAL
%-% \HDindex{PASCAL!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
and FORTRAN.
%-% \HDindex{FORTRAN!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}

\Language{} provides delayed assignment with \axiomSyntax{==}.
%-% \HDindex{assignment!delayed}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
This implements a
%-% \HDindex{delayed assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
delayed evaluation of the right-hand side and dependency
checking.

\beginImportant
The syntax for delayed assignment is
\centerline{{{\it variable} \axiom{==} {\it expression}}}
The value returned by a delayed assignment is \void{}.
\endImportant

\xtc{
Using \axiom{a} and \axiom{b} as above, these are the corresponding delayed
assignments.
}{
\spadpaste{a == 1 \bound{ad}}
}
\xtc{
}{
\spadpaste{b == a \free{ad}\bound{bd}}
}
\xtc{
The right-hand side of each delayed assignment
is left unevaluated until the
variables on the left-hand sides are evaluated.
Therefore this evaluation and \ldots
}{
\spadpaste{a \free{ad}}
}
\xtc{
this evaluation seem the same as before.
}{
\spadpaste{b \free{bd}}
}
\xtc{
If we change \axiom{a} to \axiom{2}
}{
\spadpaste{a == 2 \bound{ad2}}
}
\xtc{
then
\axiom{a} evaluates to \axiom{2}, as expected, but
}{
\spadpaste{a \free{ad2}}
}
\xtc{
the value of \axiom{b} reflects the change to \axiom{a}.
}{
\spadpaste{b \free{bd ad2}}
}

It is possible to set several variables at the same time
%-% \HDindex{assignment!multiple immediate}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
by using
%-% \HDindex{multiple immediate assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
a \spadgloss{tuple} of variables and a tuple of expressions.\footnote{A
\spadgloss{tuple} is a collection of things separated by commas, often
surrounded by parentheses.}

\beginImportant
The syntax for multiple immediate assignments is
\centerline{{{\tt ( \subscriptIt{var}{1}, \subscriptIt{var}{2}, \ldots, \subscriptIt{var}{N} ) := ( \subscriptIt{expr}{1}, \subscriptIt{expr}{2}, \ldots, \subscriptIt{expr}{N} ) }}}
The value returned by an immediate assignment is the value of
\subscriptIt{expr}{N}.
\endImportant

\xtc{
This sets \axiom{x} to \axiom{1} and \axiom{y} to \axiom{2}.
}{
\spadpaste{(x,y) := (1,2) \bound{x}\bound{y}}
}
Multiple immediate assigments are parallel in the sense that the
expressions on the right are all evaluated before any assignments
on the left are made.
However, the order of evaluation of these expressions is undefined.
\xtc{
You can use multiple immediate assignment to swap the
values held by variables.
}{
\spadpaste{(x,y) := (y,x) \free{x y}\bound{swap}}
}
\xtc{
\axiom{x} has the previous value of \axiom{y}.
}{
\spadpaste{x \free{swap}}
}
\xtc{
\axiom{y} has the previous value of \axiom{x}.
}{
\spadpaste{y \free{swap}}
}

There is no syntactic form for multiple delayed assignments.
See the discussion in
\downlink{``\ugUserDelayTitle''}{ugUserDelayPage} in Section \ugUserDelayNumber\ignore{ugUserDelay}
about how \Language{} differentiates between delayed assignments and
user functions of no arguments.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangBlocksTitle}{Blocks}
\newcommand{\ugLangBlocksNumber}{5.2.}
%
% =====================================================================
\begin{page}{ugLangBlocksPage}{5.2. Blocks}
% =====================================================================
\beginscroll

%%
%% We should handle tabs in pile correctly but so far we do not.
%%

A \spadgloss{block} is a sequence of expressions evaluated
in the order that they appear, except as modified by control expressions
such as \axiom{break},
\spadkey{break}
\axiom{return},
\spadkey{return}
\axiom{iterate} and
\spadkey{iterate}
\axiom{if-then-else} constructions.
The value of a block is the value of the expression last evaluated
in the block.

To leave a block early, use \axiomSyntax{=>}.
For example, \axiom{i < 0 => x}.
The expression before the \axiomSyntax{=>} must evaluate to
\axiom{true} or \axiom{false}.
The expression following the \axiomSyntax{=>} is the return value
for the block.

A block can be constructed in two ways:
\indent{4}
\beginitems
\item[1. ] the expressions can be separated by semicolons
and the resulting expression surrounded by parentheses, and
\item[2. ] the expressions can be written on succeeding lines with each line
indented the same number of spaces (which must be greater than zero).
%-% \HDindex{indentation}{ugLangBlocksPage}{5.2.}{Blocks}
A block entered in this form is
called a \spadgloss{pile}.
\enditems
\indent{0}
Only the first form is available if you are entering expressions
directly to \Language{}.
Both forms are available in {\bf .input} files.

\beginImportant
The syntax for a simple block of expressions entered interactively is
\centerline{{{\tt ( \subscriptIt{expression}{1}; \subscriptIt{expression}{2}; \ldots; \subscriptIt{expression}{N} )}}}
The value returned by a block is the value of an
\axiomSyntax{=>} expression, or \subscriptIt{expression}{N}
if no \axiomSyntax{=>} is encountered.
\endImportant

In {\bf .input} files, blocks can also be written using
\spadglossSee{piles}{pile}.
The examples throughout this book are assumed to come from {\bf .input} files.

\xtc{
In this example, we assign a rational number to \axiom{a} using a block
consisting of three expressions.
This block is written as a pile.
Each expression in the pile has the same indentation, in this case two
spaces to the right of the first line.
}{
\begin{spadsrc}
a :=
  i := gcd(234,672)
  i := 3*i**5 - i + 1
  1 / i
\end{spadsrc}
}
\xtc{
Here is the same block written on one line.
This is how you are required to enter it at the input prompt.
}{
\spadpaste{a := (i := gcd(234,672); i := 3*i**5 - i + 1; 1 / i)}
}
\xtc{
Blocks can be used to put several expressions on one line.
The value returned is that of the last expression.
}{
\spadpaste{(a := 1; b := 2; c := 3; [a,b,c]) \bound{a b c}}
}

\Language{} gives you two ways of writing a block and the
preferred way in an {\bf .input} file is to use a pile.
%-% \HDindex{file!input}{ugLangBlocksPage}{5.2.}{Blocks}
Roughly speaking, a pile is
a block whose constituent expressions are indented the same amount.
You begin a pile by starting a new line for the first expression,
indenting it to the right of the previous line.
You then enter the second expression on a new line, vertically aligning
it with the first line. And so on.
If you need to enter an inner pile, further indent its lines to the right
of the outer pile.
\Language{} knows where a pile ends.
It ends when a subsequent line is indented to the left of the pile or
the end of the file.

\xtc{
Blocks can be used to perform several steps before an assignment
(immediate or delayed) is made.
}{
\begin{spadsrc}[\free{a b}]
d :=
   c := a**2 + b**2
   sqrt(c * 1.3)
\end{spadsrc}
}
\xtc{
Blocks can be used in the arguments to functions.
(Here \axiom{h} is assigned \axiom{2.1 + 3.5}.)
}{
\begin{spadsrc}[\bound{h}]
h := 2.1 +
   1.0
   3.5
\end{spadsrc}
}
\xtc{
Here the second argument to \axiomFun{eval} is \axiom{x = z}, where
the value of \axiom{z} is computed in the first line of the block
starting on the second line.
}{
\begin{spadsrc}
eval(x**2 - x*y**2,
     z := %pi/2.0 - exp(4.1)
     x = z
   )
\end{spadsrc}
}
\xtc{
Blocks can be used in the clauses of \axiom{if-then-else}
expressions (see \downlink{``\ugLangIfTitle''}{ugLangIfPage} in Section \ugLangIfNumber\ignore{ugLangIf}).
}{
\spadpaste{if h > 3.1 then 1.0 else (z := cos(h); max(z,0.5)) \free{h}}
}
\xtc{
This is the pile version of the last block.
}{
\begin{spadsrc}[\free{h}]
if h > 3.1 then
    1.0
  else
    z := cos(h)
    max(z,0.5)
\end{spadsrc}
}
\xtc{
Blocks can be nested.
}{
\spadpaste{a := (b := factorial(12); c := (d := eulerPhi(22); factorial(d));b+c)}
}
\xtc{
This is the pile version of the last block.
}{
\begin{spadsrc}
a :=
  b := factorial(12)
  c :=
    d := eulerPhi(22)
    factorial(d)
  b+c
\end{spadsrc}
}

\xtc{
Since \axiom{c + d} does equal \axiom{3628855}, \axiom{a} has the value
of \axiom{c} and the last line is never evaluated.
}{
\begin{spadsrc}
a :=
  c := factorial 10
  d := fibonacci 10
  c + d = 3628855 => c
  d
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangIfTitle}{if-then-else}
\newcommand{\ugLangIfNumber}{5.3.}
%
% =====================================================================
\begin{page}{ugLangIfPage}{5.3. if-then-else}
% =====================================================================
\beginscroll

Like many other programming languages, \Language{} uses the three
keywords \spadkey{if} \axiom{if, then} \spadkey{then} and \axiom{else}
\spadkey{else} to form
%-% \HDindex{conditional}{ugLangIfPage}{5.3.}{if-then-else}
conditional expressions.
The \axiom{else} part of the conditional is optional.
The expression between the \axiom{if} and \axiom{then} keywords
is a
\spadgloss{predicate}: an expression that evaluates to or is convertible to
either {\tt true} or {\tt false}, that is,
a \axiomType{Boolean}.
%-% \HDexptypeindex{Boolean}{ugLangIfPage}{5.3.}{if-then-else}

\beginImportant
The syntax for conditional expressions is
\centerline{{{\tt if {\it predicate} then \subscriptIt{expression}{1} else \subscriptIt{expression}{2}}}}
where the \axiom{else} \subscriptIt{\it expression}{2} part is optional.
The value returned from a conditional expression is
\subscriptIt{\it expression}{1} if the predicate evaluates to \axiom{true}
and \subscriptIt{\it expression}{2} otherwise.
If no \axiom{else} clause is given, the value is always \void{}.
\endImportant

An \axiom{if-then-else} expression always returns a value.
If the
\axiom{else} clause is missing then the entire expression returns
\void{}.
If both clauses are present, the type of the value returned by \axiom{if}
is obtained by resolving the types of the values of the two clauses.
See \downlink{``\ugTypesResolveTitle''}{ugTypesResolvePage} in Section \ugTypesResolveNumber\ignore{ugTypesResolve}
for more information.

The predicate must evaluate to, or be convertible to, an object of type
\axiomType{Boolean}: {\tt true} or {\tt false}.
By default, the equal sign \spadopFrom{=}{Equation} creates
%-% \HDindex{equation}{ugLangIfPage}{5.3.}{if-then-else}
an equation.
\xtc{
This is an equation.
%-% \HDexptypeindex{Equation}{ugLangIfPage}{5.3.}{if-then-else}
In particular, it is an object of type \axiomType{Equation Polynomial Integer}.
}{
\spadpaste{x + 1 = y}
}
However, for predicates in \axiom{if} expressions, \Language{}
%-% \HDindex{equality testing}{ugLangIfPage}{5.3.}{if-then-else}
places a default target type of \axiomType{Boolean} on the
predicate and equality testing is performed.
%-% \HDexptypeindex{Boolean}{ugLangIfPage}{5.3.}{if-then-else}
Thus you need not qualify the \axiomSyntax{=} in any way.
In other contexts you may need to tell \Language{} that you want
to test for equality rather than create an equation.
In those cases, use \axiomSyntax{@} and a target type of
\axiomType{Boolean}.
See \downlink{``\ugTypesPkgCallTitle''}{ugTypesPkgCallPage} in Section \ugTypesPkgCallNumber\ignore{ugTypesPkgCall} for more information.

The compound symbol meaning ``not equal'' in \Language{} is
%-% \HDindex{inequality testing}{ugLangIfPage}{5.3.}{if-then-else}
``\texht{$\sim =$}{\axiom{~=}}''.
%-% \HDindex{\_notequal@$\sim =$}{ugLangIfPage}{5.3.}{if-then-else}
This can be used directly without a package call or a target specification.
The expression
\axiom{a} \texht{$\sim =$}{\axiom{~=}} \axiom{b} is directly translated into
\axiom{not (a = b)}.

Many other functions have return values of type \axiomType{Boolean}.
These include \axiom{<}, \axiom{<=}, \axiom{>},
\axiom{>=}, \texht{$\sim =$}{\axiom{~=}} and \axiom{member?}.
By convention, operations with names ending in \axiomSyntax{?}
return \axiomType{Boolean} values.

The usual rules for piles are suspended for conditional expressions.
In {\bf .input} files, the \axiom{then} and
\axiom{else} keywords can begin in the same column as the corresponding
\axiom{if} but may also appear to the right.
Each of the following styles of writing \axiom{if-then-else}
expressions is acceptable:
\begin{verbatim}
if i>0 then output("positive") else output("nonpositive")

if i > 0 then output("positive")
  else output("nonpositive")

if i > 0 then output("positive")
else output("nonpositive")

if i > 0
then output("positive")
else output("nonpositive")

if i > 0
  then output("positive")
  else output("nonpositive")
\end{verbatim}

A block can follow the \axiom{then} or \axiom{else} keywords.
In the following two assignments to \axiom{a}, the \axiom{then} and \axiom{else}
clauses each are followed by two-line piles.
The value returned in each is the value of the second line.

\begin{verbatim}
a :=
  if i > 0 then
    j := sin(i * pi())
    exp(j + 1/j)
  else
    j := cos(i * 0.5 * pi())
    log(abs(j)**5 + 1)

a :=
  if i > 0
    then
      j := sin(i * pi())
      exp(j + 1/j)
    else
      j := cos(i * 0.5 * pi())
      log(abs(j)**5 + 1)
\end{verbatim}
These are both equivalent to the following:
\begin{verbatim}
a :=
  if i > 0 then (j := sin(i * pi()); exp(j + 1/j))
  else (j := cos(i * 0.5 * pi()); log(abs(j)**5 + 1))
\end{verbatim}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsTitle}{Loops}
\newcommand{\ugLangLoopsNumber}{5.4.}
%
% =====================================================================
\begin{page}{ugLangLoopsPage}{5.4. Loops}
% =====================================================================
\beginscroll

A \spadgloss{loop} is an expression that contains another expression,
%-% \HDindex{loop}{ugLangLoopsPage}{5.4.}{Loops}
called the {\it loop body}, which is to be evaluated zero or more
%-% \HDindex{loop!body}{ugLangLoopsPage}{5.4.}{Loops}
times.
All loops contain the \axiom{repeat} keyword and return \void{}.
Loops can contain inner loops to any depth.

\beginImportant
The most basic loop is of the form
\centerline{{\axiom{repeat} {\it loopBody}}}
Unless {\it loopBody} contains a \axiom{break} or \axiom{return} expression,
the loop repeats forever.
The value returned by the loop is \void{}.
\endImportant

\beginmenu
    \menudownlink{{5.4.1. Compiling vs. Interpreting Loops}}{ugLangLoopsCompIntPage}
    \menudownlink{{5.4.2. return in Loops}}{ugLangLoopsReturnPage}
    \menudownlink{{5.4.3. break in Loops}}{ugLangLoopsBreakPage}
    \menudownlink{{5.4.4. break vs. {\tt =>} in Loop Bodies}}{ugLangLoopsBreakVsPage}
    \menudownlink{{5.4.5. More Examples of break}}{ugLangLoopsBreakMorePage}
    \menudownlink{{5.4.6. iterate in Loops}}{ugLangLoopsIteratePage}
    \menudownlink{{5.4.7. while Loops}}{ugLangLoopsWhilePage}
    \menudownlink{{5.4.8. for Loops}}{ugLangLoopsForInPage}
    \menudownlink{{5.4.9. for i in n..m repeat}}{ugLangLoopsForInNMPage}
    \menudownlink{{5.4.10. for i in n..m by s repeat}}{ugLangLoopsForInNMSPage}
    \menudownlink{{5.4.11. for i in n.. repeat}}{ugLangLoopsForInNPage}
    \menudownlink{{5.4.12. for x in l repeat}}{ugLangLoopsForInXLPage}
    \menudownlink{{5.4.13. ``Such that'' Predicates}}{ugLangLoopsForInPredPage}
    \menudownlink{{5.4.14. Parallel Iteration}}{ugLangLoopsParPage}
\endmenu
\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsCompIntTitle}{Compiling vs. Interpreting Loops}
\newcommand{\ugLangLoopsCompIntNumber}{5.4.1.}
%
% =====================================================================
\begin{page}{ugLangLoopsCompIntPage}{5.4.1. Compiling vs. Interpreting Loops}
% =====================================================================
\beginscroll

\Language{} tries to determine completely the type of every
object in a loop and then to translate the loop body to LISP or even to
machine code.
This translation is called \spadglossSee{compilation}{compiler}.

If \Language{} decides that it cannot compile the loop, it issues a
%-% \HDindex{loop!compilation}{ugLangLoopsCompIntPage}{5.4.1.}{Compiling vs. Interpreting Loops}
message stating the problem and then the following message:
%
\centerline{{{\bf We will attempt to step through and interpret the code.}}}
%
It is still possible that \Language{} can evaluate the loop but in
\spadgloss{interpret-code mode}.
See \downlink{``\ugUserCompIntTitle''}{ugUserCompIntPage} in Section \ugUserCompIntNumber\ignore{ugUserCompInt} where this is discussed in terms
%-% \HDindex{panic!avoiding}{ugLangLoopsCompIntPage}{5.4.1.}{Compiling vs. Interpreting Loops}
of compiling versus interpreting functions.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsReturnTitle}{return in Loops}
\newcommand{\ugLangLoopsReturnNumber}{5.4.2.}
%
% =====================================================================
\begin{page}{ugLangLoopsReturnPage}{5.4.2. return in Loops}
% =====================================================================
\beginscroll

A \axiom{return} expression is used to exit a function with
%-% \HDindex{loop!leaving via return}{ugLangLoopsReturnPage}{5.4.2.}{return in Loops}
a particular value.
In particular, if a \axiom{return} is in a loop within the
\spadkey{return}
function, the loop is terminated whenever the \axiom{return}
is evaluated.
%> This is a bug! The compiler should never accept allow
%> Void to be the return type of a function when it has to use
%> resolve to determine it.
\xtc{
Suppose we start with this.
}{
\begin{spadsrc}[\bound{f}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then return i
    i := i + 1
\end{spadsrc}
}
\xtc{
When \axiom{factorial(i)} is big enough, control passes from
inside the loop all the way outside the function, returning the
value of \axiom{i} (or so we think).
}{
\spadpaste{f() \free{f}}
}

What went wrong?
Isn't it obvious that this function should return an integer?
Well, \Language{} makes no attempt to analyze the structure of a
loop to determine if it always returns a value because, in
general, this is impossible.
So \Language{} has this simple rule: the type of the function is
determined by the type of its body, in this case a block.
The normal value of a block is the value of its last expression,
in this case, a loop.
And the value of every loop is \void{}!
So the return type of \userfun{f} is \axiomType{Void}.

There are two ways to fix this.
The best way is for you to tell \Language{} what the return type
of \axiom{f} is.
You do this by giving \axiom{f} a declaration \axiom{f: () ->
Integer} prior to calling for its value.
This tells \Language{}: ``trust me---an integer is returned.''
We'll explain more about this in the next chapter.
Another clumsy way is to add a dummy expression as follows.

\xtc{
Since we want an integer, let's stick in a dummy final expression that is
an integer and will never be evaluated.
}{
\begin{spadsrc}[\bound{f1}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then return i
    i := i + 1
  0
\end{spadsrc}
}
\xtc{
When we try \userfun{f} again we get what we wanted.
See
\downlink{``\ugUserBlocksTitle''}{ugUserBlocksPage} in Section \ugUserBlocksNumber\ignore{ugUserBlocks}
for more information.
}{
\spadpaste{f() \free{f1}}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakTitle}{break in Loops}
\newcommand{\ugLangLoopsBreakNumber}{5.4.3.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakPage}{5.4.3. break in Loops}
% =====================================================================
\beginscroll

The \axiom{break} keyword is often more useful
\spadkey{break}
in terminating
%-% \HDindex{loop!leaving via break}{ugLangLoopsBreakPage}{5.4.3.}{break in Loops}
a loop.
%>  and more in keeping with the ideas of structured programming.
A \axiom{break} causes control to transfer to the expression
immediately following the loop.
As loops always return \void{},
you cannot return a value with \axiom{break}.
That is, \axiom{break} takes no argument.

\xtc{
This example is a modification of the last example in
\texht{the previous section}{\downlink{``\ugLangLoopsReturnTitle''}{ugLangLoopsReturnPage} in Section \ugLangLoopsReturnNumber\ignore{ugLangLoopsReturn}}.
Instead of using \axiom{return}, we'll use \axiom{break}.
}{
\begin{spadsrc}[\bound{f1}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then break
    i := i + 1
  i
\end{spadsrc}
}
\xtc{
The loop terminates when \axiom{factorial(i)} gets big enough,
the last line of the function evaluates to the corresponding ``good''
value of \axiom{i}, and the function terminates, returning that value.
}{
\spadpaste{f() \free{f1}}
}
\xtc{
You can only use \axiom{break} to terminate the evaluation of one loop.
Let's consider a loop within a loop, that is, a loop with a nested loop.
First, we initialize two counter variables.
}{
\spadpaste{(i,j) := (1, 1) \bound{i}\bound{j}}
}
\xtc{
Nested loops must have multiple \axiom{break}
%-% \HDindex{loop!nested}{ugLangLoopsBreakPage}{5.4.3.}{break in Loops}
expressions at the appropriate nesting level.
How would you rewrite this so \axiom{(i + j) > 10} is only evaluated once?
}{
\begin{spadsrc}[\free{i j}]
repeat
  repeat
    if (i + j) > 10 then break
    j := j + 1
  if (i + j) > 10 then break
  i := i + 1
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakVsTitle}{break vs. {\tt =>} in Loop Bodies}
\newcommand{\ugLangLoopsBreakVsNumber}{5.4.4.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakVsPage}{5.4.4. break vs. {\tt =>} in Loop Bodies}
% =====================================================================
\beginscroll

Compare the following two loops:

\begin{verbatim}
i := 1                            i := 1
repeat                            repeat
  i := i + 1                        i := i + 1
  i > 3 => i                        if i > 3 then break
  output(i)                         output(i)
\end{verbatim}

In the example on the left, the values
\mathOrSpad{2} and \mathOrSpad{3} for \axiom{i} are displayed
but then the \axiomSyntax{=>} does not allow control to reach the call to
\axiomFunFrom{output}{OutputForm} again.
The loop will not terminate
until you run out of space or interrupt the execution.
The variable \axiom{i} will continue to be incremented because
the \axiomSyntax{=>} only means to leave the {\it block,} not the loop.

In the example on the right,
upon reaching \mathOrSpad{4}, the \axiom{break} will be
executed, and both the block and the loop will terminate.
This is one of the reasons why both \axiomSyntax{=>} and \axiom{break} are
provided.
Using a \axiom{while} clause (see below) with the \axiomSyntax{=>}
\spadkey{while}
lets you simulate the action of \axiom{break}.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakMoreTitle}{More Examples of break}
\newcommand{\ugLangLoopsBreakMoreNumber}{5.4.5.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakMorePage}{5.4.5. More Examples of break}
% =====================================================================
\beginscroll

Here we give four examples of \axiom{repeat} loops that
terminate when a value exceeds a given bound.

\texht{\vskip 1pc}{}
\xtc{
First, initialize \axiom{i} as the loop counter.
}{
\spadpaste{i := 0 \bound{i}}
}
\xtc{
Here is the first loop.
When the square of \axiom{i} exceeds \axiom{100}, the loop terminates.
}{
\begin{spadsrc}[\free{i}\bound{i1}]
repeat
  i := i + 1
  if i**2 > 100 then break
\end{spadsrc}
}
\xtc{
Upon completion, \axiom{i} should have the value \axiom{11}.
}{
\spadpaste{i \free{i1}}
}
%
%
\xtc{
Do the same thing except use \axiomSyntax{=>} instead
an \axiom{if-then} expression.
}{
\spadpaste{i := 0 \bound{i2}}
}
\xtc{
}{
\begin{spadsrc}[\free{i2}\bound{i3}]
repeat
  i := i + 1
  i**2 > 100 => break
\end{spadsrc}
}
\xtc{
}{
\spadpaste{i \free{i3}}
}
%
%
\xtc{
As a third example, we use a simple loop to compute \axiom{n!}.
}{
\spadpaste{(n, i, f) := (100, 1, 1) \bound{n}\bound{i4}\bound{f}}
}
\xtc{
Use \axiom{i} as the iteration variable and \axiom{f}
to compute the factorial.
}{
\begin{spadsrc}[\bound{f1}\bound{i5}\free{f i4 n}]
repeat
  if i > n then break
  f := f * i
  i := i + 1
\end{spadsrc}
}
\xtc{
Look at the value of \axiom{f}.
}{
\spadpaste{f \free{f1}}
}
%
%
\xtc{
Finally, we show an example of nested loops.
First define a four by four matrix.
}{
\spadpaste{m := matrix [[21,37,53,14], [8,-24,22,-16], [2,10,15,14], [26,33,55,-13]] \bound{m2}}
}
\xtc{
Next, set row counter \axiom{r} and column counter \axiom{c} to
\mathOrSpad{1}.
Note: if we were writing a function, these would all be local
variables rather than global workspace variables.
}{
\spadpaste{(r, c) := (1, 1) \bound{r}\bound{c}}
}
\xtc{
Also, let \axiom{lastrow} and
\axiom{lastcol} be the final row and column index.
}{
\spadpaste{(lastrow, lastcol) := (nrows(m), ncols(m)) \bound{lastrow}\bound{lastcol}\free{m2}}
}
%
\xtc{
Scan the rows looking for the first negative element.
We remark that you can reformulate this example in a better, more
concise form by using a \axiom{for} clause with \axiom{repeat}.
See
\downlink{``\ugLangLoopsForInTitle''}{ugLangLoopsForInPage} in Section \ugLangLoopsForInNumber\ignore{ugLangLoopsForIn}
for more information.
}{
\begin{spadsrc}[\free{m2 r c lastrow lastcol}]
repeat
  if r > lastrow then break
  c := 1
  repeat
    if c > lastcol then break
    if elt(m,r,c) < 0 then
      output [r, c, elt(m,r,c)]
      r := lastrow
      break     -- don't look any further
    c := c + 1
  r := r + 1
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsIterateTitle}{iterate in Loops}
\newcommand{\ugLangLoopsIterateNumber}{5.4.6.}
%
% =====================================================================
\begin{page}{ugLangLoopsIteratePage}{5.4.6. iterate in Loops}
% =====================================================================
\beginscroll

\Language{} provides an \axiom{iterate} expression that
\spadkey{iterate}
skips over the remainder of a loop body and starts the next loop iteration.
\xtc{
We first initialize a counter.
}{
\spadpaste{i := 0 \bound{i}}
}
\xtc{
Display the even integers from \axiom{2} to \axiom{5}.
}{
\begin{spadsrc}[\free{i}]
repeat
  i := i + 1
  if i > 5 then break
  if odd?(i) then iterate
  output(i)
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsWhileTitle}{while Loops}
\newcommand{\ugLangLoopsWhileNumber}{5.4.7.}
%
% =====================================================================
\begin{page}{ugLangLoopsWhilePage}{5.4.7. while Loops}
% =====================================================================
\beginscroll

The \axiom{repeat} in a loop can be modified by adding one or
more \axiom{while} clauses.
\spadkey{while}
Each clause contains a \spadgloss{predicate}
immediately following the \axiom{while} keyword.
The predicate is tested {\it before}
the evaluation of the body of the loop.
The loop body is evaluated whenever the predicates in a \axiom{while}
clause are all \axiom{true}.

\beginImportant
The syntax for a simple loop using \axiom{while} is
\centerline{{\axiom{while} {\it predicate} \axiom{repeat} {\it loopBody}}}
The {\it predicate} is evaluated before {\it loopBody} is evaluated.
A \axiom{while} loop terminates immediately when {\it predicate}
evaluates to \axiom{false} or when a \axiom{break} or \axiom{return}
expression is evaluated in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

\xtc{
Here is a simple example of using \axiom{while} in a loop.
We first initialize the counter.
}{
\spadpaste{i := 1 \bound{i}}
}
\xtc{
The steps involved in computing this example are
(1) set \axiom{i} to \axiom{1}, (2) test the condition \axiom{i < 1} and
determine that it is not true, and (3) do not evaluate the
loop body and therefore do not display \axiom{"hello"}.
}{
\begin{spadsrc}[\free{i}]
while i < 1 repeat
  output "hello"
  i := i + 1
\end{spadsrc}
}
\xtc{
If you have multiple predicates to be tested use the
logical \axiom{and} operation to separate them.
\Language{} evaluates these predicates from left to right.
}{
\spadpaste{(x, y) := (1, 1) \bound{x}\bound{y}}
}
\xtc{
}{
\begin{spadsrc}[\free{x y}]
while x < 4 and y < 10 repeat
  output [x,y]
  x := x + 1
  y := y + 2
\end{spadsrc}
}
\xtc{
A \axiom{break} expression can be included in a loop body to terminate a
loop even if the predicate in any \axiom{while} clauses are not \axiom{false}.
}{
\spadpaste{(x, y) := (1, 1) \bound{x1}\bound{y1}}
}
\xtc{
This loop has multiple \axiom{while} clauses and the loop terminates
before any one of their conditions evaluates to \axiom{false}.
}{
\begin{spadsrc}[\free{x1 y1}]
while x < 4 while y < 10 repeat
  if x + y > 7 then break
  output [x,y]
  x := x + 1
  y := y + 2
\end{spadsrc}
}
\xtc{
Here's a different version of the nested loops that looked
for the first negative element in a matrix.
}{
\spadpaste{m := matrix [[21,37,53,14], [8,-24,22,-16], [2,10,15,14], [26,33,55,-13]] \bound{m2}}
}
\xtc{
Initialized the row index to \axiom{1} and
get the number of rows and columns.
If we were writing a function, these would all be
local variables.
}{
\spadpaste{r := 1 \bound{r}}
}
\xtc{
}{
\spadpaste{(lastrow, lastcol) := (nrows(m), ncols(m)) \bound{lastrow}\bound{lastcol}\free{m2}}
}
%
\xtc{
Scan the rows looking for the first negative element.
}{
\begin{spadsrc}[\free{m2 r lastrow lastcol}]
while r <= lastrow repeat
  c := 1  -- index of first column
  while c <= lastcol repeat
    if elt(m,r,c) < 0 then
      output [r, c, elt(m,r,c)]
      r := lastrow
      break     -- don't look any further
    c := c + 1
  r := r + 1
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInTitle}{for Loops}
\newcommand{\ugLangLoopsForInNumber}{5.4.8.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInPage}{5.4.8. for Loops}
% =====================================================================
\beginscroll

\Language{} provides the \axiom{for}
\spadkey{for}
and \axiom{in}
\spadkey{in}
keywords in \axiom{repeat} loops,
allowing you to iterate across all
%-% \HDindex{iteration}{ugLangLoopsForInPage}{5.4.8.}{for Loops}
elements of a list, or to have a variable take on integral values
from a lower bound to an upper bound.
We shall refer to these modifying clauses of \axiom{repeat} loops as
\axiom{for} clauses.
These clauses can be present in addition to \axiom{while} clauses.
As with all other types of \axiom{repeat} loops, \axiom{break} can
\spadkey{break}
be used to prematurely terminate the evaluation of the loop.

\beginImportant
The syntax for a simple loop using \axiom{for} is
\centerline{{\axiom{for} {\it iterator} \axiom{repeat} {\it loopBody}}}
The {\it iterator} has several forms.
Each form has an end test which is evaluated
before {\it loopBody} is evaluated.
A \axiom{for} loop terminates immediately when the end test
succeeds (evaluates to \axiom{true}) or when a \axiom{break} or \axiom{return}
expression is evaluated in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNMTitle}{for i in n..m repeat}
\newcommand{\ugLangLoopsForInNMNumber}{5.4.9.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNMPage}{5.4.9. for i in n..m repeat}
% =====================================================================
\beginscroll

If \axiom{for}
\spadkey{for}
is followed by a variable name, the \axiom{in}
\spadkey{in}
keyword and then an integer segment of the form \axiom{n..m},
%-% \HDindex{segment}{ugLangLoopsForInNMPage}{5.4.9.}{for i in n..m repeat}
the end test for this loop is the predicate \axiom{i > m}.
The body of the loop is evaluated \axiom{m-n+1} times if this
number is greater than 0.
If this number is less than or equal to 0, the loop body is not evaluated
at all.

The variable \axiom{i} has the value
\axiom{n, n+1, ..., m} for successive iterations
of the loop body.
The loop variable is a \spadgloss{local variable}
within the loop body: its value is not available outside the loop body
and its value and type within the loop body completely mask any outer
definition of a variable with the same name.

%
\xtc{
This loop prints the values of
\texht{${10}^3$, ${11}^3$, and $12^3$}{\axiom{10**3, 11**3, and 12**3}}:
}{
\spadpaste{for i in 10..12 repeat output(i**3)}
}
%
\xtc{
Here is a sample list.
}{
\spadpaste{a := [1,2,3] \bound{a}}
}
\xtc{
Iterate across this list, using \axiomSyntax{.} to access the elements of a list and
the \axiomFun{\#} operation to count its elements.
}{
\spadpaste{for i in 1..\#a repeat output(a.i) \free{a}}
}
%
This type of iteration is applicable to anything that uses \axiomSyntax{.}.
You can also use it with functions that use indices to extract elements.
%
\xtc{
Define \axiom{m} to be a matrix.
}{
\spadpaste{m := matrix [[1,2],[4,3],[9,0]] \bound{m}}
}
\xtc{
Display the rows of \axiom{m}.
}{
\spadpaste{for i in 1..nrows(m) repeat output row(m,i) \free{m}}
}
%
You can use \axiom{iterate} with \axiom{for}-loops.
\spadkey{iterate}
\xtc{
Display the even integers in a segment.
}{
\begin{spadsrc}
for i in 1..5 repeat
  if odd?(i) then iterate
  output(i)
\end{spadsrc}
}

See \downlink{`Segment'}{SegmentXmpPage}\ignore{Segment} for more information about segments.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNMSTitle}{for i in n..m by s repeat}
\newcommand{\ugLangLoopsForInNMSNumber}{5.4.10.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNMSPage}{5.4.10. for i in n..m by s repeat}
% =====================================================================
\beginscroll

By default, the difference between values taken on by a variable in loops
such as \axiom{for i in n..m repeat ...} is \mathOrSpad{1}.
It is possible to supply another, possibly negative, step value by using
the \axiom{by}
\spadkey{by}
keyword along with \axiom{for} and \axiom{in}.
Like the upper and lower bounds, the step value following the
\axiom{by} keyword must be an integer.
Note that the loop
\axiom{for i in 1..2 by 0 repeat output(i)}
will not terminate by itself, as the step value does not change the index
from its initial value of \mathOrSpad{1}.

\xtc{
This expression displays the odd integers between two bounds.
}{
\spadpaste{for i in 1..5 by 2 repeat output(i)}
}
\xtc{
Use this to display the numbers in reverse order.
}{
\spadpaste{for i in 5..1 by -2 repeat output(i)}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNTitle}{for i in n.. repeat}
\newcommand{\ugLangLoopsForInNNumber}{5.4.11.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNPage}{5.4.11. for i in n.. repeat}
% =====================================================================
\beginscroll

If the value after the \axiomSyntax{..}
is omitted, the loop has no end test.
A potentially infinite loop is thus created.
The variable is given the successive values \axiom{n, n+1, n+2, ...}
and the loop is terminated only if a \axiom{break} or \axiom{return}
expression is evaluated in the loop body.
However you may also add some other modifying clause on the
\axiom{repeat} (for example, a \axiom{while} clause) to stop the loop.

\xtc{
This loop displays the integers greater than or equal to \axiom{15}
and less than the first prime greater than \axiom{15}.
}{
\spadpaste{for i in 15.. while not prime?(i) repeat output(i)}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInXLTitle}{for x in l repeat}
\newcommand{\ugLangLoopsForInXLNumber}{5.4.12.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInXLPage}{5.4.12. for x in l repeat}
% =====================================================================
\beginscroll

Another variant of the \axiom{for} loop has the form:
\centerline{{{\it \axiom{for} x \axiom{in} list \axiom{repeat} loopBody}}}
This form is used when you want to iterate directly over the
elements of a list.
In this form of the \axiom{for} loop, the variable
\axiom{x} takes on the value of each successive element in \axiom{l}.
The end test is most simply stated in English: ``are there no more
\axiom{x} in \axiom{l}?''

\xtc{
If \axiom{l} is this list,
}{
\spadpaste{l := [0,-5,3] \bound{l}}
}
\xtc{
display all elements of \axiom{l}, one per line.
}{
\spadpaste{for x in l repeat output(x) \free{l}}
}

Since the list constructing expression \axiom{expand [n..m]} creates the
list \axiom{[n, n+1, ..., m]}\footnote{This list is empty if \axiom{n >
m}.}, you might be tempted to think that the loops
\begin{verbatim}
for i in n..m repeat output(i)
\end{verbatim}
and
\begin{verbatim}
for x in expand [n..m] repeat output(x)
\end{verbatim}
are equivalent.
The second form first creates the list
\axiom{expand [n..m]} (no matter how large it might be) and
then does the iteration.
The first form potentially runs in much less space, as the index variable
\axiom{i} is simply incremented once per loop and the list is not actually
created.
Using the first form is much more efficient.
%
\xtc{
Of course, sometimes you really want to iterate across a specific list.
This displays each of the factors of \axiom{2400000}.
}{
\spadpaste{for f in factors(factor(2400000)) repeat output(f)}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInPredTitle}{``Such that'' Predicates}
\newcommand{\ugLangLoopsForInPredNumber}{5.4.13.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInPredPage}{5.4.13. ``Such that'' Predicates}
% =====================================================================
\beginscroll

A \axiom{for} loop can be followed by a \axiomSyntax{|} and then a
predicate.
The predicate qualifies the use of the values from the iterator following
the \axiom{for}.
Think of the vertical bar
\axiomSyntax{|} as the phrase ``such that.''
\xtc{
This loop expression
prints out the integers \axiom{n} in the given segment
such that \axiom{n} is odd.
}{
\spadpaste{for n in 0..4 | odd? n repeat output n}
}

\beginImportant
A \axiom{for} loop can also be written
\centerline{{\axiom{for} {\it iterator} \axiom{|} {\it predicate}  \axiom{repeat} {\it loopBody}}}
which is equivalent to:
\centerline{{\axiom{for} {\it iterator} \axiom{repeat if}}}
\centerline{{{\it predicate} \axiom{then} {\it loopBody} \axiom{else} \axiom{iterate}}}
\endImportant

The predicate need not refer only to the variable in the \axiom{for} clause:
any variable in an outer scope can be part of the predicate.
\xtc{
In this example, the predicate on the inner \axiom{for} loop uses
\axiom{i} from the outer loop and the \axiom{j} from the \axiom{for}
%-% \HDindex{iteration!nested}{ugLangLoopsForInPredPage}{5.4.13.}{``Such that'' Predicates}
clause that it directly modifies.
}{
\begin{spadsrc}
for i in 1..50 repeat
  for j in 1..50 | factorial(i+j) < 25 repeat
    output [i,j]
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsParTitle}{Parallel Iteration}
\newcommand{\ugLangLoopsParNumber}{5.4.14.}
%
% =====================================================================
\begin{page}{ugLangLoopsParPage}{5.4.14. Parallel Iteration}
% =====================================================================
\beginscroll

The last example of
\texht{the previous section}{\downlink{``\ugLangLoopsForInPredTitle''}{ugLangLoopsForInPredPage} in Section \ugLangLoopsForInPredNumber\ignore{ugLangLoopsForInPred}}
gives an example of
\spadgloss{nested iteration}: a loop is contained
%-% \HDindex{iteration!nested}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
in another loop.
%-% \HDindex{iteration!parallel}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
Sometimes you want to iterate across two lists in parallel, or perhaps
you want to traverse a list while incrementing a variable.

\beginImportant
The general syntax of a repeat loop is
\centerline{{{\tt \subscriptIt{iterator}{1} \subscriptIt{iterator}{2} \ldots \subscriptIt{iterator}{N} repeat {\it loopBody}}}}
where each {\it iterator} is either a \axiom{for} or a \axiom{while} clause.
The loop terminates immediately when the end test of any {\it iterator}
succeeds or when a \axiom{break} or \axiom{return} expression is evaluated
in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

\xtc{
Here we write a loop to iterate across
two lists, computing the sum of the pairwise product
of elements. Here is the first list.
}{
\spadpaste{l := [1,3,5,7] \bound{l}}
}
\xtc{
And the second.
}{
\spadpaste{m := [100,200] \bound{m}}
}
\xtc{
The initial value of the sum counter.
}{
\spadpaste{sum := 0 \bound{sum}}
}
\xtc{
The last two elements of \axiom{l} are not used in the calculation
because \axiom{m} has two fewer elements than \axiom{l}.
}{
\begin{spadsrc}[\bound{doit}\free{sum l m}]
for x in l for y in m repeat
    sum := sum + x*y
\end{spadsrc}
}
\xtc{
Display the ``dot product.''
}{
\spadpaste{sum \free{doit}}
}

\xtc{
Next, we write a loop to compute the sum of the products of the loop elements with
their positions in the loop.
}{
\spadpaste{l := [2,3,5,7,11,13,17,19,23,29,31,37] \bound{l1}}
}
\xtc{
The initial sum.
}{
\spadpaste{sum := 0 \bound{sum1}}
}
\xtc{
Here looping stops when the list \axiom{l} is exhausted, even though
the \axiom{for i in 0..} specifies no terminating condition.
}{
\spadpaste{for i in 0.. for x in l repeat sum := i * x \bound{doit1}\free{sum1 l1}}
}
\xtc{
Display this weighted sum.
}{
\spadpaste{sum \free{doit1}}
}

When \axiomSyntax{|} is used to qualify any of the \axiom{for} clauses in a
parallel iteration, the variables in the predicates can be from an outer
scope or from a \axiom{for} clause in or to the left of a modified clause.

This is correct:
\begin{verbatim}
for i in 1..10 repeat
  for j in 200..300 | odd? (i+j) repeat
    output [i,j]
\end{verbatim}
This is not correct since the variable \axiom{j} has not been
defined outside the inner loop.
\begin{verbatim}
for i in 1..10 | odd? (i+j) repeat  -- wrong, j not defined
  for j in 200..300 repeat
    output [i,j]
\end{verbatim}

%>% *********************************************************************
%>\head{subsection}{Mixing Loop Modifiers}{ugLangLoopsMix}
%>% *********************************************************************

\xtc{
This example shows that it is possible to mix several of the
%-% \HDindex{loop!mixing modifiers}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
forms of \axiom{repeat} modifying clauses on a loop.
}{
\begin{spadsrc}
for i in 1..10
    for j in 151..160 | odd? j
      while i + j < 160 repeat
        output [i,j]
\end{spadsrc}
}
%
Here are useful rules for composing loop expressions:
\indent{4}
\beginitems
\item[1. ] \axiom{while} predicates can only refer to variables that
are global (or in an outer scope)
or that are defined in \axiom{for} clauses to the left of the
predicate.
\item[2. ] A ``such that'' predicate (something following \axiomSyntax{|})
must directly follow a \axiom{for} clause and can only refer to
variables that are global (or in an outer scope)
or defined in the modified \axiom{for} clause
or any \axiom{for} clause to the left.
\enditems
\indent{0}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangItsTitle}{Creating Lists and Streams with Iterators}
\newcommand{\ugLangItsNumber}{5.5.}
%
% =====================================================================
\begin{page}{ugLangItsPage}{5.5. Creating Lists and Streams with Iterators}
% =====================================================================
\beginscroll

All of what we did for loops in \downlink{``\ugLangLoopsTitle''}{ugLangLoopsPage} in Section \ugLangLoopsNumber\ignore{ugLangLoops}
%-% \HDindex{iteration}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
can be transformed into expressions that create lists
%-% \HDindex{list!created by iterator}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
and streams.
%-% \HDindex{stream!created by iterator}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
The \axiom{repeat,} \axiom{break} or \axiom{iterate} words are not used but
all the other ideas carry over.
Before we give you the general rule, here are some examples which
give you the idea.

\xtc{
This creates a simple list of the integers from \axiom{1} to \axiom{10}.
}{
\spadpaste{list := [i for i in 1..10] \bound{list}}
}
\xtc{
Create a stream of the integers greater than or equal to \axiom{1}.
}{
\spadpaste{stream := [i for i in 1..] \bound{stream}}
}
\xtc{
This is a list of the prime integers between \axiom{1} and \axiom{10},
inclusive.
}{
\spadpaste{[i for i in 1..10 | prime? i]}
}
\xtc{
This is a stream of the prime integers greater than or equal to \axiom{1}.
}{
\spadpaste{[i for i in 1..   | prime? i]}
}
\xtc{
This is a list of the integers between \axiom{1} and \axiom{10},
inclusive, whose squares are less than \axiom{700}.
}{
\spadpaste{[i for i in 1..10 while i*i < 700]}
}
\xtc{
This is a stream of the integers greater than or equal to \axiom{1}
whose squares are less than \axiom{700}.
}{
\spadpaste{[i for i in 1..   while i*i < 700]}
}

Got the idea?
Here is the general rule.
%-% \HDindex{collection}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}

\beginImportant
The general syntax of a collection is
\centerline{{{\tt [ {\it collectExpression} \subscriptIt{iterator}{1}  \subscriptIt{iterator}{2}  \ldots  \subscriptIt{iterator}{N} ]}}}
where each \subscriptIt{iterator}{i} is either a \axiom{for} or a
\axiom{while} clause.
The loop terminates immediately when the end test of any
\subscriptIt{iterator}{i} succeeds or when a \axiom{return} expression is
evaluated in {\it collectExpression}.
The value returned by the collection is either a list or a stream of
elements, one for each iteration of the {\it collectExpression}.
\endImportant

Be careful when you use \axiom{while}
%-% \HDindex{stream!using while @{using {\tt while}}}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
to create a stream.
By default, \Language{} tries to compute and display the first ten elements
of a stream.
If the \axiom{while} condition is not satisfied quickly, \Language{}
can spend a long (possibly infinite) time trying to compute
%-% \HDindex{stream!number of elements computed}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
the elements.
Use \spadcmd{)set streams calculate} to change the default
to something else.
%-% \HDsyscmdindex{set streams calculate}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
This also affects the number of terms computed and displayed for power
series.
For the purposes of this book, we have used this system
command to display fewer than ten terms.
\xtc{
Use nested iterators to create lists of
%-% \HDindex{iteration!nested}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
lists which can then be given as an argument to \axiomFun{matrix}.
}{
\spadpaste{matrix [[x**i+j for i in 1..3] for j in 10..12]}
}
\xtc{
You can also create lists of streams, streams of lists and
streams of streams.
Here is a stream of streams.
}{
\spadpaste{[[i/j for i in j+1..] for j in 1..]}
}
\xtc{
You can use parallel iteration across lists and streams to create
%-% \HDindex{iteration!parallel}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
new lists.
}{
\spadpaste{[i/j for i in 3.. by 10 for j in 2..]}
}
\xtc{
Iteration stops if the end of a list or stream is reached.
}{
\spadpaste{[i**j for i in 1..7 for j in 2.. ]}
}
%\xtc{
%or a while condition fails.
%}{
%\spadcommand{[i**j for i in 1..  for j in 2.. while i + j < 5 ]}
%}
\xtc{
As with loops, you can combine these modifiers to make very
complicated conditions.
}{
\spadpaste{[[[i,j] for i in 10..15 | prime? i] for j in 17..22 | j = squareFreePart j]}
}

See \downlink{`List'}{ListXmpPage}\ignore{List} and \downlink{`Stream'}{StreamXmpPage}\ignore{Stream} for more information on creating and
manipulating lists and streams, respectively.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangStreamsPrimesTitle}{An Example: Streams of Primes}
\newcommand{\ugLangStreamsPrimesNumber}{5.6.}
%
% =====================================================================
\begin{page}{ugLangStreamsPrimesPage}{5.6. An Example: Streams of Primes}
% =====================================================================
\beginscroll

We conclude this chapter with an example of the creation and manipulation
of infinite streams of prime integers.
This might be useful for experiments with numbers or other applications
where you are using sequences of primes over and over again.
As for all streams, the stream of primes is only computed as far out as you
need.
Once computed, however, all the primes up to that point are saved for
future reference.

Two useful operations provided by the \Language{} library are
\axiomFunFrom{prime?}{IntegerPrimesPackage} and
\axiomFunFrom{nextPrime}{IntegerPrimesPackage}.
A straight-forward way to create a stream of
prime numbers is to start with the stream of positive integers \axiom{[2,..]} and
filter out those that are prime.
\xtc{
Create a stream of primes.
}{
\spadpaste{primes : Stream Integer := [i for i in 2.. | prime? i]}
}
A more elegant way, however, is to use the \axiomFunFrom{generate}{Stream}
operation from \axiomType{Stream}.
Given an initial value \axiom{a} and a function \axiom{f},
\axiomFunFrom{generate}{Stream}
constructs the stream \axiom{[a, f(a), f(f(a)), ...]}.
This function gives you the quickest method of getting the stream of primes.
\xtc{
This is how you use
\axiomFunFrom{generate}{Stream} to
generate an infinite stream of primes.
}{
\spadpaste{primes := generate(nextPrime,2)}
}
\xtc{
Once the stream is generated, you might only be interested in
primes starting at a particular value.
}{
\spadpaste{smallPrimes := [p for p in primes | p > 1000] \bound{smallPrimes}}
}
\xtc{
Here are the first 11 primes greater than 1000.
}{
\spadpaste{[p for p in smallPrimes for i in 1..11] \free{smallPrimes}}
}
\xtc{
Here is a stream of primes between 1000 and 1200.
}{
\spadpaste{[p for p in smallPrimes while p < 1200] \free{smallPrimes}}
}
\xtc{
To get these expanded into a finite stream,
you call \axiomFunFrom{complete}{Stream} on the stream.
}{
\spadpaste{complete \%}
}
\xtc{
Twin primes are consecutive odd number pairs which are prime.
Here is the stream of twin primes.
}{
\spadpaste{twinPrimes := [[p,p+2] for p in primes | prime?(p + 2)]}
}
\xtc{
Since we already have the primes computed we can
avoid the call to \axiomFunFrom{prime?}{IntegerPrimesPackage}
by using a double iteration.
This time we'll just generate a stream of the first of the twin primes.
}{
\spadpaste{firstOfTwins:= [p for p in primes for q in rest primes | q=p+2]}
}

Let's try to compute the infinite stream of triplet primes,
the set of primes \axiom{p} such that \axiom{[p,p+2,p+4]}
are primes. For example, \axiom{[3,5,7]} is a triple prime.
We could do this by a triple \axiom{for} iteration.
A more economical way is to use \userfun{firstOfTwins}.
This time however, put a semicolon at the end of the line.

\xtc{Create the stream of firstTriplets.
Put a semicolon at the end so that no
elements are computed.
}{
\spadpaste{firstTriplets := [p for p in firstOfTwins for q in rest firstOfTwins | q = p+2];}
}

What happened?
As you know, by default
\Language{} displays the first ten
elements of a stream when you first display it.
And, therefore, it needs to compute them!
If you want {\it no} elements computed, just terminate the expression by a
semicolon (\axiomSyntax{;}).\footnote{
Why does this happen? The semi-colon prevents the display of the
result of evaluating the expression.
Since no stream elements are needed for display (or anything else, so far),
none are computed.
}

\xtc{
Compute the first triplet prime.
}{
\spadpaste{firstTriplets.1}
}

If you want to compute another, just ask for it.
But wait a second!
Given three consecutive odd integers, one of them must be divisible
by 3. Thus there is only one triplet prime.
But suppose that you did not know this and wanted to know what was the
tenth triplet prime.
\begin{verbatim}
firstTriples.10
\end{verbatim}
To compute the tenth triplet prime, \Language{} first must compute the second,
the third, and so on.
But since there isn't even a second triplet prime, \Language{} will
compute forever.
Nonetheless, this effort can produce a useful result.
After waiting a bit, hit
\texht{\fbox{\bf Ctrl}--\fbox{\bf c}}{{\bf Ctrl-c}}.
The system responds as follows.
\begin{verbatim}
   >> System error:
   Console interrupt.
   You are being returned to the top level of
   the interpreter.
\end{verbatim}
Let's say that you want to know how many primes have been computed.
Issue
\begin{verbatim}
numberOfComputedEntries primes
\end{verbatim}
and, for this discussion, let's say that the result is \axiom{2045.}
\xtc{
How big is the \eth{\axiom{2045}} prime?
}{
\spadpaste{primes.2045}
}

What you have learned is that there are no triplet primes between 5 and
17837.
Although this result is well known (some might even say trivial), there
are many experiments you could make where the result is not known.
What you see here is a paradigm for testing of hypotheses.
Here our hypothesis could have been: ``there is more than one triplet
prime.''
We have tested this hypothesis for 17837 cases.
With streams, you can let your machine run, interrupt it to see how far
it has progressed,
then start it up and let it continue from where it left off.

%> RDJ note to RSS:
%> Expressions not statements or lines--
%>   By an expression I mean any syntactically correct program fragment.
%>   Everything in AXIOM is an expression since every fragment has a value and a type.
%>   In most languages including LISP, a "statement" is different from an expression:
%>   it is executed for side-effect only and an error is incurred if you assign it a value.
%>   This "gimmick" takes care of incomplete expressions such as "if x > 0 then y" in blocks.
%>   In LISP, "u := (if x > 0 then y)" is illegal but in AXIOM it is legal.
%>   Also, in AXIOM the value of a repeat loop is void even though you might be
%>   be able to prove that it always returns a valid value (you have an example of this)!
%>   This will be considered a bug not a feature. But it is how things stand.
%>   In any case---this point should be in a box somewhere since it is key
%>   to a user's understanding to the language. I am not sure where. You only
%>   gain an appreciation for it after are awhile in chapter 5.
\endscroll
\autobuttons
\end{page}
%