]>
In this chapter we look at some of the basic components of the Axiom language that you can use interactively. We show how to create a block of expressions, how to form loops and list iterations, how to modify the sequential evaluation of a block and how to use 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.
A variable in Axiom refers to a value. A variable has a name beginning with an uppercase or lowercase alphabetic character, ``%'', or ``!''. Successive characters (if any) can be any of the above, digits, or ``?''. Case is distinguished. The following are all examples of valid, distinct variable names:
The ``:='' operator is the immediate assignment operator. assignment:immediate Use it to associate a value with a variable. immediate assignment
The syntax for immediate assignment for a single variable is
variable expression
The value returned by an immediate assignment is the value of
expression.
The right-hand side of the expression is evaluated, yielding . This value is then assigned to .
The right-hand side of the expression is evaluated, yielding . This value is then assigned to . Thus and both have the value after the sequence of assignments.
What is the value of if is assigned the value ?
As you see, the value of is left unchanged.
This is what we mean when we say this kind of assignment is immediate; has no dependency on after the initial assignment. This is the usual notion of assignment found in programming languages such as C, C language:assignment PASCAL PASCAL:assignment and FORTRAN. FORTRAN:assignment
Axiom provides delayed assignment with ``==''. assignment:delayed This implements a delayed assignment delayed evaluation of the right-hand side and dependency checking.
The syntax for delayed assignment is
variable expression
The value returned by a delayed assignment is the unique value of Void.
Using and as above, these are the corresponding delayed assignments.
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 ...
this evaluation seem the same as before.
If we change to
then evaluates to , as expected, but
the value of reflects the change to .
It is possible to set several variables at the same time assignment:multiple immediate by using multiple immediate assignment a tuple of variables and a tuple of expressions. Note that a tuple is a collection of things separated by commas, often surrounded by parentheses.
The syntax for multiple immediate assignments is
( , , ..., ) := ( , , ..., )
The value returned by an immediate assignment is the value of
.
This sets to and to .
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.
You can use multiple immediate assignment to swap the values held by variables.
has the previous value of .
has the previous value of .
There is no syntactic form for multiple delayed assignments. See the discussion in section ugUserDelay about how Axiom differentiates between delayed assignments and user functions of no arguments.
A block is a sequence of expressions evaluated in the order that they appear, except as modified by control expressions such as break, break return, return iterate and iterate 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 ``=>''. For example, . The expression before the ``=>'' must evaluate to true or false. The expression following the ``=>'' is the return value for the block.
A block can be constructed in two ways:
Only the first form is available if you are entering expressions directly to Axiom. Both forms are available in .input files.
The syntax for a simple block of expressions entered interactively is
( ; ; ...; )
The value returned by a block is the value of an => expression,
or if no => is encountered.
In .input files, blocks can also be written using piles. The examples throughout this book are assumed to come from .input files.
In this example, we assign a rational number to 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.
Here is the same block written on one line. This is how you are required to enter it at the input prompt.
Blocks can be used to put several expressions on one line. The value returned is that of the last expression.
Axiom gives you two ways of writing a block and the preferred way in an .input file is to use a pile. file:input 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. Axiom 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.
Blocks can be used to perform several steps before an assignment (immediate or delayed) is made.
Blocks can be used in the arguments to functions. (Here is assigned .)
Here the second argument to eval is , where the value of is computed in the first line of the block starting on the second line.
Blocks can be used in the clauses of if-then-else expressions (see ugLangIf ).
This is the pile version of the last block.
Blocks can be nested.
This is the pile version of the last block.
Since does equal , has the value of and the last line is never evaluated.
Like many other programming languages, Axiom uses the three keywords if if, then then and else else to form conditional conditional expressions. The else part of the conditional is optional. The expression between the if and then keywords is a predicate: an expression that evaluates to or is convertible to either true or false, that is, a Boolean. Boolean
The syntax for conditional expressions is
if predicate then else
where the else part is optional. The
value returned from a conditional expression is
if the predicate evaluates to true and
otherwise. If no else clause is given,
the value is always the unique value of Void.
An if-then-else expression always returns a value. If the else clause is missing then the entire expression returns the unique value of Void. If both clauses are present, the type of the value returned by if is obtained by resolving the types of the values of the two clauses. See ugTypesResolve for more information.
The predicate must evaluate to, or be convertible to, an object of type Boolean: true or false. By default, the equal sign = creates equation an equation.
This is an equation. Equation In particular, it is an object of type Equation Polynomial Integer.
However, for predicates in if expressions, Axiom equality testing places a default target type of Boolean on the predicate and equality testing is performed. Boolean Thus you need not qualify the ``='' in any way. In other contexts you may need to tell Axiom that you want to test for equality rather than create an equation. In those cases, use ``@'' and a target type of Boolean. See section ugTypesPkgCall for more information.
The compound symbol meaning ``not equal'' in Axiom is inequality testing ``''. _notequal@ This can be used directly without a package call or a target specification. The expression is directly translated into not .
Many other functions have return values of type Boolean. These include ``<'', ``<='', ``>'', ``>='', ``'' and ``member?''. By convention, operations with names ending in ``?'' return Boolean values.
The usual rules for piles are suspended for conditional expressions. In .input files, the then and else keywords can begin in the same column as the corresponding if but may also appear to the right. Each of the following styles of writing if-then-else expressions is acceptable:
A block can follow the then or else keywords. In the following two assignments to a, the then and else clauses each are followed by two-line piles. The value returned in each is the value of the second line.
These are both equivalent to the following:
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:
All of what we did for loops in ugLangLoops iteration can be transformed into expressions that create lists list:created by iterator and streams. stream:created by iterator The repeat, break or 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.
This creates a simple list of the integers from to .
Create a stream of the integers greater than or equal to .
This is a list of the prime integers between and , inclusive.
This is a stream of the prime integers greater than or equal to .
This is a list of the integers between and , inclusive, whose squares are less than .
This is a stream of the integers greater than or equal to whose squares are less than .
Here is the general rule. collection
The general syntax of a collection is
[ collectExpression ... ]
where each is either a for or a while
clause. The loop terminates immediately when the end test of any
succeeds or when a return expression is
evaluated in collectExpression. The value returned by the
collection is either a list or a stream of elements, one for each
iteration of the collectExpression.
Be careful when you use while stream:using while @{using while} to create a stream. By default, Axiom tries to compute and display the first ten elements of a stream. If the while condition is not satisfied quickly, Axiom can spend a long (possibly infinite) time trying to compute stream:number of elements computed the elements. Use )set streams calculate to change the default to something else. set streams calculate 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.
Use nested iterators to create lists of iteration:nested lists which can then be given as an argument to matrix.
You can also create lists of streams, streams of lists and streams of streams. Here is a stream of streams.
You can use parallel iteration across lists and streams to create iteration:parallel new lists.
Iteration stops if the end of a list or stream is reached.
As with loops, you can combine these modifiers to make very complicated conditions.
See List (section ListXmpPage ) and Stream (section StreamXmpPage ) for more information on creating and manipulating lists and streams, respectively.
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 Axiom library are prime?prime?IntegerPrimesPackage and nextPrimenextPrimeIntegerPrimesPackage. A straight-forward way to create a stream of prime numbers is to start with the stream of positive integers and filter out those that are prime.
Create a stream of primes.
A more elegant way, however, is to use the generategenerateStream operation from Stream. Given an initial value and a function , generategenerateStream constructs the stream . This function gives you the quickest method of getting the stream of primes.
This is how you use generategenerateStream to generate an infinite stream of primes.
Once the stream is generated, you might only be interested in primes starting at a particular value.
Here are the first 11 primes greater than 1000.
Here is a stream of primes between 1000 and 1200.
To get these expanded into a finite stream, you call completecompleteStream on the stream.
Twin primes are consecutive odd number pairs which are prime. Here is the stream of twin primes.
Since we already have the primes computed we can avoid the call to prime?prime?IntegerPrimesPackage by using a double iteration. This time we'll just generate a stream of the first of the twin primes.
Let's try to compute the infinite stream of triplet primes, the set of primes such that are primes. For example, is a triple prime. We could do this by a triple for iteration. A more economical way is to use firstOfTwins. This time however, put a semicolon at the end of the line.
Create the stream of firstTriplets. Put a semicolon at the end so that no elements are computed.
What happened? As you know, by default Axiom displays the first ten elements of a stream when you first display it. And, therefore, it needs to compute them! If you want no elements computed, just terminate the expression by a semicolon (``;''). 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.
Compute the first triplet prime.
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 . 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.
To compute the tenth triplet prime, Axiom first must compute the second, the third, and so on. But since there isn't even a second triplet prime, Axiom will compute forever. Nonetheless, this effort can produce a useful result. After waiting a bit, hit Ctrl-c. The system responds as follows.
If you want to know how many primes have been computed, type:
and, for this discussion, let's say that the result is . How big is the -th prime?
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.