]>
A loop is an expression that contains another expression, loop called the loop body, which is to be evaluated zero or more loop:body times. All loops contain the repeat keyword and return the unique value of Void. Loops can contain inner loops to any depth.
The most basic loop is of the form
repeat loopBody
Unless loopBody contains a break or return expression, the
loop repeats forever. The value returned by the loop is the unique
value of Void.
Axiom 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 compilation.
If Axiom decides that it cannot compile the loop, it issues a loop:compilation message stating the problem and then the following message:
We will attempt to step through and interpret the code.
It is still possible that Axiom can evaluate the loop but in interpret-code mode. See section ugUserCompInt where this is discussed in terms panic:avoiding of compiling versus interpreting functions.
A return expression is used to exit a function with loop:leaving via return a particular value. In particular, if a return is in a loop within the return function, the loop is terminated whenever the return is evaluated.
Suppose we start with this.
When factorial(i) is big enough, control passes from inside the loop all the way outside the function, returning the value of (or so we think).
What went wrong? Isn't it obvious that this function should return an integer? Well, Axiom 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 Axiom 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 the unique value of Void.! So the return type of f is Void.
There are two ways to fix this. The best way is for you to tell Axiom what the return type of is. You do this by giving a declaration f:()->Integer prior to calling for its value. This tells Axiom: ``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.
Since we want an integer, let's stick in a dummy final expression that is an integer and will never be evaluated.
When we try f again we get what we wanted. See ugUserBlocks for more information.
The break keyword is often more useful break in terminating loop:leaving via break a loop. A break causes control to transfer to the expression immediately following the loop. As loops always return the unique value of Void., you cannot return a value with break. That is, break takes no argument.
This example is a modification of the last example in the previous section ugLangLoopsReturn . Instead of using return, we'll use break.
The loop terminates when factorial(i) gets big enough, the last line of the function evaluates to the corresponding ``good'' value of , and the function terminates, returning that value.
You can only use 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.
Nested loops must have multiple break loop:nested expressions at the appropriate nesting level. How would you rewrite this so (i + j) > 10 is only evaluated once?
Compare the following two loops:
In the example on the left, the values and for are displayed but then the ``=>'' does not allow control to reach the call to outputoutputOutputForm again. The loop will not terminate until you run out of space or interrupt the execution. The variable will continue to be incremented because the ``=>'' only means to leave the block, not the loop.
In the example on the right, upon reaching , the break will be executed, and both the block and the loop will terminate. This is one of the reasons why both ``=>'' and break are provided. Using a while clause (see below) with the ``=>'' while lets you simulate the action of break.
Here we give four examples of repeat loops that terminate when a value exceeds a given bound.
First, initialize as the loop counter.
Here is the first loop. When the square of exceeds , the loop terminates.
Upon completion, should have the value .
Do the same thing except use ``=>'' instead an if-then expression.
As a third example, we use a simple loop to compute .
Use as the iteration variable and to compute the factorial.
Look at the value of .
Finally, we show an example of nested loops. First define a four by four matrix.
Next, set row counter and column counter to . Note: if we were writing a function, these would all be local variables rather than global workspace variables.
Also, let lastrow and lastcol be the final row and column index.
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 for clause with repeat. See ugLangLoopsForIn for more information.
Axiom provides an iterate expression that iterate skips over the remainder of a loop body and starts the next loop iteration.
We first initialize a counter.
Display the even integers from to .
The repeat in a loop can be modified by adding one or more while clauses. while Each clause contains a predicate immediately following the while keyword. The predicate is tested before the evaluation of the body of the loop. The loop body is evaluated whenever the predicates in a while clause are all true.
The syntax for a simple loop using while is
while predicate repeat loopBody
The predicate is evaluated before loopBody is evaluated.
A while loop terminates immediately when predicate evaluates
to false or when a break or return expression is evaluated in
loopBody. The value returned by the loop is the unique value of
Void.
Here is a simple example of using while in a loop. We first initialize the counter.
The steps involved in computing this example are
(1) set to ,
(2) test the condition and determine that it is not true, and
(3) do not evaluate the loop body and therefore do not display .
If you have multiple predicates to be tested use the logical and operation to separate them. Axiom evaluates these predicates from left to right.
A break expression can be included in a loop body to terminate a loop even if the predicate in any while clauses are not false.
This loop has multiple while clauses and the loop terminates before any one of their conditions evaluates to false.
Here's a different version of the nested loops that looked for the first negative element in a matrix.
Initialized the row index to and get the number of rows and columns. If we were writing a function, these would all be local variables.
Scan the rows looking for the first negative element.
Axiom provides the for for and in in keywords in repeat loops, allowing you to iterate across all iteration 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 repeat loops as for clauses. These clauses can be present in addition to while clauses. As with all other types of repeat loops, break can break be used to prematurely terminate the evaluation of the loop.
The syntax for a simple loop using for is
for iterator repeat loopBody
The iterator has several forms. Each form has an end test which is evaluated before loopBody is evaluated. A for loop terminates immediately when the end test succeeds (evaluates to true) or when a break or return expression is evaluated in loopBody. The value returned by the loop is the unique value of Void.\
If for for is followed by a variable name, the in in keyword and then an integer segment of the form , segment the end test for this loop is the predicate . The body of the loop is evaluated 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 has the value for successive iterations of the loop body.The loop variable is a 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.
This loop prints the values of , , and :
Here is a sample list.
Iterate across this list, using ``.'' to access the elements of a list and the ``#'' operation to count its elements.
This type of iteration is applicable to anything that uses ``.''. You can also use it with functions that use indices to extract elements.
Define to be a matrix.
Display the rows of .
You can use iterate with for-loops.iterate
Display the even integers in a segment.
See section SegmentXmpPage for more information about segments.
By default, the difference between values taken on by a variable in loops such as for i in n..m repeat ... is . It is possible to supply another, possibly negative, step value by using the by by keyword along with for and in . Like the upper and lower bounds, the step value following the by keyword must be an integer. Note that the loop 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 .
This expression displays the odd integers between two bounds.
Use this to display the numbers in reverse order.
If the value after the ``..'' is omitted, the loop has no end test. A potentially infinite loop is thus created. The variable is given the successive values and the loop is terminated only if a break or return expression is evaluated in the loop body. However you may also add some other modifying clause on the repeat (for example, a while clause) to stop the loop.
This loop displays the integers greater than or equal to and less than the first prime greater than .
Another variant of the for loop has the form:
for x in list repeat loopBody
This form is used when you want to iterate directly over the elements of a list. In this form of the for loop, the variable x takes on the value of each successive element in l. The end test is most simply stated in English: ``are there no more x in l?''
If l is this list,
display all elements of l, one per line.
Since the list constructing expression expand[n..m] creates the list . Note that this list is empty if . You might be tempted to think that the loops
and
are equivalent. The second form first creates the list 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 is simply incremented once per loop and the list is not actually created. Using the first form is much more efficient.
Of course, sometimes you really want to iterate across a specific list. This displays each of the factors of .
A for loop can be followed by a ``|'' and then a predicate. The predicate qualifies the use of the values from the iterator following the for. Think of the vertical bar ``|'' as the phrase ``such that.''
This loop expression prints out the integers in the given segment such that is odd.
A for loop can also be written
which is equivalent to:
The predicate need not refer only to the variable in the for clause: any variable in an outer scope can be part of the predicate.
In this example, the predicate on the inner for loop uses from the outer loop and the from the for iteration:nested clause that it directly modifies.
The last example of the previous section ugLangLoopsForInPred gives an example of nested iteration: a loop is contained iteration:nested in another loop. iteration:parallel Sometimes you want to iterate across two lists in parallel, or perhaps you want to traverse a list while incrementing a variable.
The general syntax of a repeat loop is
where each iterator is either a for or a while clause. The
loop terminates immediately when the end test of any iterator
succeeds or when a break or return expression is evaluated in loopBody. The value returned by the loop is the unique value of Void.
Here we write a loop to iterate across two lists, computing the sum of the pairwise product of elements. Here is the first list.
And the second.
The initial value of the sum counter.
The last two elements of are not used in the calculation because has two fewer elements than .
Display the ``dot product.''
Next, we write a loop to compute the sum of the products of the loop elements with their positions in the loop.
The initial sum.
Here looping stops when the list is exhausted, even though the specifies no terminating condition.
Display this weighted sum.
When ``|'' is used to qualify any of the for clauses in a parallel iteration, the variables in the predicates can be from an outer scope or from a for clause in or to the left of a modified clause.
This is correct:
This is not correct since the variable has not been defined outside the inner loop.
This example shows that it is possible to mix several of the loop:mixing modifiers forms of repeat modifying clauses on a loop.
Here are useful rules for composing loop expressions: