]>
When we start cataloging the gains in tools sitting on a computer, the benefits of software are amazing. But, if the benefits of software are so great, why do we worry about making it easier -- don't the ends pay for the means? We worry becuase making such software is extraordinarily hard and almost no one can do it -- the detail is exhausting, the creativity required is extreme, the hours of failure upon failure requiring patience and persistence would tax anyone claiming to be sane. Yet we require people with such characteristics be found and employed and employed cheaply.
-- Christopher Alexander
(from Patterns of Software by Richard Gabriel)
Welcome to the Axiom environment for interactive computation and problem solving. Consider this chapter a brief, whirlwind tour of the Axiom world. We introduce you to Axiom's graphics and the Axiom language. Then we give a sampling of the large variety of facilities in the Axiom system, ranging from the various kinds of numbers, to data types (like lists, arrays, and sets) and mathematical objects (like matrices, integrals, and differential equations). We conclude with the discussion of system commands and an interactive ``undo.''
Before embarking on the tour, we need to brief those readers working interactively with Axiom on some details.
You need to know how to start the Axiom system and how to stop it. We assume that Axiom has been correctly installed on your machine (as described in another Axiom document).
To begin using Axiom, issue the command axiom to the Axiom operating system shell. axiom @ axiom There is a brief pause, some start-up messages, and then one or more windows appear.
If you are not running Axiom under the X Window System, there is only one window (the console). At the lower left of the screen there is a prompt that prompt looks like
When you want to enter input to Axiom, you do so on the same line after the prompt. The ``1'' in ``(1)'', also called the equation number, is the computation step number and is incremented step number after you enter Axiom statements. Note, however, that a system command such as )clear all may change the step number in other ways. We talk about step numbers more when we discuss system commands and the workspace history facility.
If you are running Axiom under the X Window System, there may be two X Window System windows: the console window (as just described) and the HyperDoc main menu. Hyper@{HyperDoc} HyperDoc is a multiple-window hypertext system that lets you window view Axiom documentation and examples on-line, execute Axiom expressions, and generate graphics. If you are in a graphical windowing environment, it is usually started automatically when Axiom begins. If it is not running, issue )hd to start it. We discuss the basics of HyperDoc in Chapter ugHyper .
To interrupt an Axiom computation, hold down the interrupt Ctrl (control) key and press c. This brings you back to the Axiom prompt.
To exit from Axiom, move to the console window, stopping @{stopping Axiom} type )quit exiting @{exiting Axiom} at the input prompt and press the Enter key. You will probably be prompted with the following message:
Please enter y or yes if you really want to leave the
interactive environment and return to the operating system
You should respond yes, for example, to exit Axiom.
We are purposely vague in describing exactly what your screen looks like or what messages Axiom displays. Axiom runs on a number of different machines, operating systems and window environments, and these differences all affect the physical look of the system. You can also change the way that Axiom behaves via system commands described later in this chapter and in Appendix A. System commands are special commands, like )set, that begin with a closing parenthesis and are used to change your environment. For example, you can set a system variable so that you are not prompted for confirmation when you want to leave Axiom.
If you are using Axiom under the X Window System, the Clef command line editor Clef command line editor is probably available and installed. With this editor you can recall previous lines with the up and down arrow keys. To move forward and backward on a line, use the right and left arrows. You can use the Insert key to toggle insert mode on or off. When you are in insert mode, the cursor appears as a large block and if you type anything, the characters are inserted into the line without deleting the previous ones.
If you press the Home key, the cursor moves to the beginning of the line and if you press the End key, the cursor moves to the end of the line. Pressing Ctrl-End deletes all the text from the cursor to the end of the line.
Clef also provides Axiom operation name completion for operation name completion a limited set of operations. If you enter a few letters and then press the Tab key, Clef tries to use those letters as the prefix of an Axiom operation name. If a name appears and it is not what you want, press Tab again to see another name.
You are ready to begin your journey into the world of Axiom.
In this document we have followed these typographical conventions:
This document contains over 2500 examples of Axiom input and output. All examples were run though Axiom and their output was created in TeX form by the Axiom TexFormat package. We have deleted system messages from the example output if those messages are not important for the discussions in which the examples appear.
The Axiom language is a rich language for performing interactive computations and for building components of the Axiom library. Here we present only some basic aspects of the language that you need to know for the rest of this chapter. Our discussion here is intentionally informal, with details unveiled on an ``as needed'' basis. For more information on a particular construct, we suggest you consult the index.
For arithmetic expressions, use the ``+'' and ``-'' operator as in mathematics. Use ``*'' for multiplication, and ``**'' for exponentiation. To create a fraction, use ``/''. When an expression contains several operators, those of highest precedence are evaluated first. For arithmetic operators, ``**'' has highest precedence, ``*'' and ``/'' have the next highest precedence, and ``+'' and ``-'' have the lowest precedence.
Axiom puts implicit parentheses around operations of higher precedence, and groups those of equal precedence from left to right.
The above expression is equivalent to this.
If an expression contains subexpressions enclosed in parentheses, the parenthesized subexpressions are evaluated first (from left to right, from inside out).
Use the percent sign ``%'' to refer to the last result. result:previous Also, use ``%%" to refer to previous results. percentpercent@{%%} ``%%(-1)'' is equivalent to ``%'', ``%%(-2)'' returns the next to the last result, and so on. ``%%(1)'' returns the result from step number 1, ``%%(2)'' returns the result from step number 2, and so on. ``%%(0)'' is not defined.
This is ten to the tenth power.
This is the last result minus one.
This is the last result.
This is the result from step number 1.
Everything in Axiom has a type. The type determines what operations you can perform on an object and how the object can be used. Chapter~ugTypes is dedicated to the interactive use of types. Several of the final chapters discuss how types are built and how they are organized in the Axiom library.
Positive integers are given type PositiveInteger.
Negative ones are given type Integer. This fine distinction is helpful to the Axiom interpreter.
Here a positive integer exponent gives a polynomial result.
Here a negative integer exponent produces a fraction.
A symbol is a literal used for the input of things like the ``variables'' in polynomials and power series.
We use the three symbols , , and in entering this polynomial.
A symbol has a name beginning with an uppercase or lowercase alphabetic symbol:naming character, ``%'', or ``!''. Successive characters (if any) can be any of the above, digits, or ``?''. Case is distinguished: the symbol points is different from the symbol Points.
A symbol can also be used in Axiom as a variable. A variable refers to a value. To assign a value to a variable, variable:naming the operator ``:='' assignment is used. Axiom actually has two forms of assignment: immediate assignment, as discussed here, and delayed assignment. See Section ugLangAssign for details. A variable initially has no restrictions on the kinds of declaration values to which it can refer.
This assignment gives the value (an integer) to a variable named .
This gives the value (a polynomial) to .
To restrict the types of objects that can be assigned to a variable, use a declaration
After a variable is declared to be of some type, only values of that type can be assigned to that variable.
The declaration for forces values assigned to to be converted to integer values.
If no such conversion is possible, Axiom refuses to assign a value to .
A type declaration can also be given together with an assignment. The declaration can assist Axiom in choosing the correct operations to apply.
Any number of expressions can be given on input line. Just separate them by semicolons. Only the result of evaluating the last expression is displayed.
These two expressions have the same effect as the previous single expression.
The type of a symbol is either Symbol or Variable(name) where name is the name of the symbol.
By default, the interpreter gives this symbol the type Variable(q).
When multiple symbols are involved, Symbol is used.
What happens when you try to use a symbol that is the name of a variable?
Use a single quote ``''' before quote the name to get the symbol.
Quoting a name creates a symbol by preventing evaluation of the name as a variable. Experience will teach you when you are most likely going to need to use a quote. We try to point out the location of such trouble spots.
Objects of one type can usually be ``converted'' to objects of several other types. To convert an object to a new type, use the ``::'' infix operator. Conversion is discussed in detail in ugTypesConvert. For example, to display an object, it is necessary to convert the object to type OutputForm.
This produces a polynomial with rational number coefficients.
Create a quotient of polynomials with integer coefficients by using ``::''.
Some conversions can be performed automatically when Axiom tries to evaluate your input. Others conversions must be explicitly requested.
As we saw earlier, when you want to add or subtract two values, you place the arithmetic operator ``+'' or ``-'' between the two arguments denoting the values. To use most other Axiom operations, however, you use another syntax: function:calling write the name of the operation first, then an open parenthesis, then each of the arguments separated by commas, and, finally, a closing parenthesis. If the operation takes only one argument and the argument is a number or a symbol, you can omit the parentheses.
This calls the operation factor with the single integer argument .
This is a call to divide with the two integer arguments and .
This calls quatern with four floating-point arguments.
This is the same as factorial(10).
An operation that returns a Boolean value (that is, true or false) frequently has a name suffixed with a question mark (``?''). For example, the even? operation returns true if its integer argument is an even number, false otherwise.
An operation that can be destructive on one or more arguments usually has a name ending in a exclamation point (``!''). This actually means that it is allowed to update its arguments but it is not required to do so. For example, the underlying representation of a collection type may not allow the very last element to be removed and so an empty object may be returned instead. Therefore it is important that you use the object returned by the operation and not rely on a physical change having occurred within the object. Usually destructive operations are provided for efficiency reasons.
Axiom provides several macros for your convenience.See ugUserMacros for a discussion on how to write your own macros. Macros are names macro:predefined (or forms) that expand to larger expressions for commonly used values.
| %i | The square root of -1. |
| %e | The base of the natural logarithm. |
| %pi | . |
| %infinity | . |
| %plusInfinity | . |
| %minusInfinity | . |
%i %e %pi pi@{ (= %pi)} %infinity infinity@{ (= %infinity)} %plusInfinity %minusInfinity
To display all the macros (along with anything you have defined in the workspace), issue the system command )display all.
When you enter Axiom expressions from your keyboard, there will be times when they are too long to fit on one line. Axiom does not care how long your lines are, so you can let them continue from the right margin to the left side of the next line.
Alternatively, you may want to enter several shorter lines and have Axiom glue them together. To get this glue, put an underscore (_) at the end of each line you wish to continue.
is the same as if you had entered
Axiom statements in an input file (see Section ugInOutIn ), can use indentation to indicate the program structure . (see Section ugLangBlocks ).
Comment statements begin with two consecutive hyphens or two consecutive plus signs and continue until the end of the line.
The comment beginning with ``--'' is ignored by Axiom.
There is no way to write long multi-line comments other than starting each line with ``--'' or ``++''.
Axiom distinguishes very carefully between different kinds of numbers, how they are represented and what their properties are. Here are a sampling of some of these kinds of numbers and some things you can do with them.
Integer arithmetic is always exact.
Integers can be represented in factored form.
Results stay factored when you do arithmetic. Note that the is automatically factored for you.
Integers can also be displayed to bases other than 10. This is an integer in base 11.
Roman numerals are also available for those special occasions. Roman numerals
Rational number arithmetic is also exact.
To factor fractions, you have to pmap factor onto the numerator and denominator.
SingleInteger refers to machine word-length integers.
In English, this expression means `` as a small integer''.
Machine double-precision floating-point numbers are also available for numeric and graphical applications.
The normal floating-point type in Axiom, Float, is a software implementation of floating-point numbers in which the exponent and the mantissa may have any number of digits. The types Complex(Float) and Complex(DoubleFloat) are the corresponding software implementations of complex floating-point numbers.
This is a floating-point approximation to about twenty digits. floating point The ``::'' is used here to change from one kind of object (here, a rational number) to another (a floating-point number).
Use digitsdigitsFloat to change the number of digits in the representation. This operation returns the previous value so you can reset it later.
To digits of precision, the number appears to be an integer.
Increase the precision to forty digits and try again.
Here are complex numbers with rational numbers as real and complex numbers imaginary parts.
The standard operations on complex numbers are available.
You can factor complex integers.
Complex numbers with floating point parts are also available.
The real and imaginary parts can be symbolic.
Of course, you can do complex arithmetic with these also.
Every rational number has an exact representation as a repeating decimal expansion
A rational number can also be expressed as a continued fraction.
Also, partial fractions can be used and can be displayed in a partial fraction compact format fraction:partial
or expanded format.
Like integers, bases (radices) other than ten can be used for rational numbers. Here we use base eight.
Of course, there are complex versions of these as well. Axiom decides to make the result a complex rational number.
You can also use Axiom to manipulate fractional powers. radical
You can also compute with integers modulo a prime.
Arithmetic is then done modulo .
Since is prime, you can invert nonzero values.
You can also compute modulo an integer that is not a prime.
All of the usual arithmetic operations are available.
Inversion is not available if the modulus is not a prime number. Modular arithmetic and prime fields are discussed in Section ugxProblemFinitePrime .
This defines to be an algebraic number, that is, a root of a polynomial equation.
Computations with are reduced according to the polynomial equation.
Define to be an algebraic number involving .
Do some arithmetic.
To expand and simplify this, call ratDenom to rationalize the denominator.
If we do this, we should get .
But we need to rationalize the denominator again.
Types Quaternion and Octonion are also available. Multiplication of quaternions is non-commutative, as expected.
Axiom has a large variety of data structures available. Many data structures are particularly useful for interactive computation and others are useful for building applications. The data structures of Axiom are organized into category hierarchies.
A list, Lists are discussed in Section ListXmpPage, is the most commonly used data structure in Axiom for holding objects all of the same type. The name list is short for ``linked-list of nodes.'' Each node consists of a value (firstfirstList) and a link (restrestList) that points to the next node, or to a distinguished value denoting the empty list. To get to, say, the third element, Axiom starts at the front of the list, then traverses across two links to the third node.
Write a list of elements using square brackets with commas separating the elements.
This is the value at the third node. Alternatively, you can say .
Many operations are defined on lists, such as: empty?, to test that a list has no elements; cons, to create a new list with first element and rest ; reverse, to create a new list with elements in reverse order; and sort, to arrange elements in order.
An important point about lists is that they are ``mutable'': their constituent elements and links can be changed ``in place.'' To do this, use any of the operations whose names end with the character ``!''.
The operation concat!concat!List replaces the last link of the list to point to some other list . Since refers to the original list, this change is seen by .
A cyclic list is a list with a ``cycle'': list:cyclic a link pointing back to an earlier node of the list. cyclic list To create a cycle, first get a node somewhere down the list.
Use setrest!setrest!List to change the link emanating from that node to point back to an earlier part of the list.
A stream is a structure that (potentially) has an infinite number of distinct elements. Think of a stream as an ``infinite list'' where elements are computed successively. Streams are discussed in Section{StreamXmpPage}.
Create an infinite stream of factored integers. Only a certain number of initial elements are computed and displayed.
Axiom represents streams by a collection of already-computed elements together with a function to compute the next element ``on demand.'' Asking for the -th element causes elements through to be evaluated.
Streams can also be finite or cyclic. They are implemented by a linked list structure similar to lists and have many of the same operations. For example, first and rest are used to access elements and successive nodes of a stream.
A one-dimensional array is another data structure used to hold objects of the same type OnedimensionalArray is discussed in Section OneDimensionalArrayXmpPage. Unlike lists, one-dimensional arrays are inflexible---they are array:one-dimensional implemented using a fixed block of storage. Their advantage is that they give quick and equal access time to any element.
A simple way to create a one-dimensional array is to apply the operation oneDimensionalArray to a list of elements.
One-dimensional arrays are also mutable: you can change their constituent elements ``in place.''
However, one-dimensional arrays are not flexible structures. You cannot destructively concat! them together.
Examples of datatypes similar to OneDimensionalArray are: Vector (vectors are mathematical structures implemented by one-dimensional arrays), String (arrays of ``characters,'' represented by byte vectors), and Bits (represented by ``bit vectors'').
A vector of 32 bits, each representing the Boolean value .
A flexible array (FlexibleArray is discussed in Section FlexibleArrayXmpPage ) is a cross between a list array:flexible and a one-dimensional array. Like a one-dimensional array, a flexible array occupies a fixed block of storage. Its block of storage, however, has room to expand. When it gets full, it grows (a new, larger block of storage is allocated); when it has too much room, it contracts.
Create a flexible array of three elements.
Insert some elements between the second and third elements.
Flexible arrays are used to implement ``heaps.'' A heap is an example of a data structure called a priority queue, where elements are ordered with respect to one another. A heap (Heap is discussed in Section HeapXmpPage ) is organized so as to optimize insertion and extraction of maximum elements. The extract! operation returns the maximum element of the heap, after destructively removing that element and reorganizing the heap so that the next maximum element is ready to be delivered.
An easy way to create a heap is to apply the operation heap to a list of values.
This loop extracts elements one-at-a-time from until the heap is exhausted, returning the elements as a list in the order they were extracted.
A binary tree is a ``tree'' with at most two branches tree per node: it is either empty, or else is a node consisting of a value, and a left and right subtree (again, binary trees). (BinarySearchTrees are discussed in Section BinarySearchTreeXmpPage ) Examples of binary tree types are BinarySearchTree, PendantTree, TournamentTree, and BalancedBinaryTree.
A binary search tree is a binary tree such that, tree:binary search for each node, the value of the node is binary search tree greater than all values (if any) in the left subtree, and less than or equal all values (if any) in the right subtree.
A balanced binary tree is useful for doing modular computations. balanced binary tree Given a list of moduli, tree:balanced binary modTree produces a balanced binary tree with the values at its leaves.
A set is a collection of elements where duplication and order is irrelevant. Sets are discussed in Section SetXmpPage Sets are always finite and have no corresponding structure like streams for infinite collections.
Create sets using braces ``{`` and ``}'' rather than brackets.
A multiset is a set that keeps track of the number of duplicate values. Multisets are discussed in Section MultiSetXmpPage
For all the primes between 2 and 1000, find the distribution of .
A table is conceptually a set of ``key--value'' pairs and is a generalization of a multiset. For examples of tables, see AssociationList, HashTable, KeyedAccessFile, Library, SparseTable, StringTable, and Table. The domain Table(Key, Entry) provides a general-purpose type for tables with values of type indexed by keys of type .
Compute the above distribution of primes using tables. First, let denote an empty table of keys and values, each of type Integer.
We define a function howMany to return the number of values of a given modulus seen so far. It calls search which returns the number of values stored under the key in table , or ``failed'' if no such value is yet stored in under .
In English, this says ``Define as follows. First, let be the value of search. Then, if has the value , return the value ; otherwise return .''
Run through the primes to create the table, then print the table. The expression t.m := howMany(m) updates the value in table stored under key .
A record is an example of an inhomogeneous collection of objects.See ugTypesRecords for details. A record consists of a set of named selectors that can be used to access its components. Record@{\sf Record}
Declare that can only be assigned a record with two prescribed fields.
Give a value, using square brackets to enclose the values of the fields.
Give a raise.
A union is a data structure used when objects have multiple types.See ugTypesUnions for details. Union@{\sf Union}
Let be either an integer or a string value.
Give a name.
All told, there are over forty different data structures in Axiom. Using the domain constructors described in Chapter ugDomains you can add your own data structure or extend an existing one. Choosing the right data structure for your application may be the key to obtaining good performance.
To get higher dimensional aggregates, you can create one-dimensional aggregates with elements that are themselves aggregates, for example, lists of lists, one-dimensional arrays of lists of multisets, and so on. For applications requiring two-dimensional homogeneous aggregates, you will likely find two-dimensional arrays matrix and matrices most useful. array:two-dimensional
The entries in TwoDimensionalArray and Matrix objects are all the same type, except that those for Matrix must belong to a Ring. You create and access elements in roughly the same way. Since matrices have an understood algebraic structure, certain algebraic operations are available for matrices but not for arrays. Because of this, we limit our discussion here to Matrix, that can be regarded as an extension of TwoDimensionalArray. See TwoDimensionalArray for more information about arrays. For more information about Axiom's linear algebra facilities, see Matrix, Permanent, SquareMatrix, Vector, see Section ugProblemEigen (computation of eigenvalues and eigenvectors), and Section ugProblemLinPolEqn (solution of linear and polynomial equations).
You can create a matrix from a list of lists, matrix:creating where each of the inner lists represents a row of the matrix.
The ``collections'' construct (see ugLangIts) is useful for creating matrices whose entries are given by formulas. matrix:Hilbert
Let denote the three by three Vandermonde matrix.
Use this syntax to extract an entry in the matrix.
You can also pull out a row or a column.
You can do arithmetic.
You can perform operations such as transpose, trace, and determinant.
Axiom provides you with a very large library of predefined operations and objects to compute with. You can use the Axiom library of constructors to create new objects dynamically of quite arbitrary complexity. For example, you can make lists of matrices of fractions of polynomials with complex floating point numbers as coefficients. Moreover, the library provides a wealth of operations that allow you to create and manipulate these objects.
For many applications, you need to interact with the interpreter and write some Axiom programs to tackle your application. Axiom allows you to write functions interactively, function thereby effectively extending the system library. Here we give a few simple examples, leaving the details to Chapter ugUser .
We begin by looking at several ways that you can define the ``factorial'' function in Axiom. The first way is to give a function:piece-wise definition piece-wise definition of the function. piece-wise function definition This method is best for a general recurrence relation since the pieces are gathered together and compiled into an efficient iterative function. Furthermore, enough previously computed values are automatically saved so that a subsequent call to the function can pick up from where it left off.
Define the value of fact at .