SlideShare a Scribd company logo
1 of 48
Download to read offline
An Introduction to MAGMA
Don Taylor
The University of Sydney
13 February 2012
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 1 / 31
A little history
MAGMA is a programming language for computer algebra, geometry,
combinatorics and number theory. It has extensive support for group
theoretic computations and can handle permutation groups, matrix groups
and finitely-presented groups. A more complete list of applications will be
given later.
The language was developed by John Cannon and his team at the
University of Sydney and was released in December 1993. It replaced
CAYLEY, also developed by John Cannon.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 2 / 31
MAGMA 2.18
The name ‘MAGMA’ comes from Bourbaki (and Serre) where it is used to
denote a set with one or more binary operations without any additional
axioms. Thus a magma is the most basic of algebraic structures.
Today, in 2012, Version 2.18 of MAGMA is a huge system with more than
5000 pages of documentation in 13 volumes.
MAGMA can be used both interactively and as a programming language.
The core of MAGMA is programmed in C but a large part of its functionality
resides in package files written in the MAGMA user language.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 3 / 31
Outline
The following topics will be illustrated by examples drawn from a selection
of MAGMA packages.
1 Using MAGMA interactively
� Using files.
� Printing.
� The help system.
2 Essential data structures: sets, sequences, records and associative
arrays.
3 Functions and procedures, function expressions and maps.
4 MAGMA’s type system and coercion.
5 The MAGMA language and styles of programming.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 4 / 31
The MAGMA design
The design principles underpinning both the user language and system
architecture are based on ideas from universal algebra and category theory.
The MAGMA language attempts to approximate the usual mathematical
modes of thought and notation as closely as possible. In particular, the
principal constructs in the user language are sets, algebraic structures such
as groups, rings and fields and morphisms.
[The following three slides are from the MAGMA documentation.]
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 5 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA language
Imperative language with standard imperative-style statements and
procedures
A functional subset providing closures, higher-order functions, and
partial evaluation
General aggregate data types based on algebraic notions: set,
sequence, mapping, magma
Universal structure constructors providing a general mechanism for the
construction of magmas and mappings
Simple but powerful notation for constructing sets and sequences in a
natural mathematical style
Set and sequence operations which are implemented with a strong
emphasis on efficiency
Coercion between magmas (including automatic coercion)
A package mechanism to support modular program construction
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The MAGMA environment
Command completion and interactive line editing
History system with recall and editing of previous lines
A hierarchical online help facility
Packages containing user-defined intrinsics with automatic compilation
Environment variables for configuring style of output, etc.
Get/set functions and procedures for configuring style, etc.
Verbose options for built-in functions
Logging of output, redirection of I/O
Special file type for fully-featured file I/O
Ability to execute system commands from within Magma
Input/output pipes for communication with external programs
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
The main components of MAGMA
The MAGMA Language and
System
Groups
Semigroups and Monoids
Rings and Fields
Commutative Rings
Linear Algebra and Module
Theory
Lattices and Quadratic Forms
Algebras
Representation Theory
Homological Algebra
Lie Theory
Algebraic Geometry
Finite Incidence Geometry
Differential Galois Theory
Error-correcting Codes
Cryptography
Mathematical Databases
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 8 / 31
Interacting with MAGMA
To start, simply type
magma
To stop, type Ctrl-D or
> quit;
Every instruction to MAGMA must end with a semicolon ( ; ) but don’t
type the > sign—this is MAGMA’s prompt character.
When developing MAGMA programs it is useful to put the commands in a
file. To load the commands from a file named lecture1.m, type
> load "lecture1.m";
If you would like MAGMA to pause after each line of input, use
> iload "lecture1.m";
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 9 / 31
Using MAGMA interactively — Tab completion
Suppose that you want to find the first few Legendre polynomials. There
are many ways to achieve this in MAGMA.
One of the first things to do is to check the documentation to find out if
there is already a function which does what you want.
Alternatively you can use the MAGMA help system. For example, if you type
Legendre at a MAGMA prompt and then press the Tab key you will see the
following:
> Legendre
LegendreEquation LegendrePolynomial
LegendreModel LegendreSymbol
If you now type P followed by Tab and a semicolon:
> LegendrePolynomial;
you will see some information about how to use this function.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 10 / 31
Using MAGMA interactively — the Help system
To get more detailed information, put a question mark before the name of
the command:
> ?LegendrePolynomial
Depending on how MAGMA is installed either a web browser will open
showing the online help for the function or MAGMA’s internal help system
will provide information about the command.
To print the 7th Legendre polynomial simply issue the command
> LegendrePolynomial(7);
The output is
429/16*$.1^7 - 693/16*$.1^5 + 315/16*$.1^3 - 35/16*$.1
To get more readable output it is possible to assign a more useful name,
such as z, to the indeterminate $.1. We shall see how to do this on the
next slide.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 11 / 31
Legendre Polynomials: Rodrigues’ formula
Suppose that you didn’t discover that MAGMA has a built-in function for
Legendre polynomials. In that case you can define them yourself using
either a direct or recursive formula.
For the direct method we use Rodrigue’s formula
Pn(z) =
1
2n
n!
dn
dzn
(z2
− 1)n
.
To set this up in MAGMA we need the polynomial ring in the indeterminate
z over the rational numbers.
> R<z> := PolynomialRing(Rationals());
> P := func< n | Derivative((z^2-1)^n,n)/(2^n*Factorial(n))>;
> P(7);
429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z
> P(7) eq LegendrePolynomial(7);
true
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 12 / 31
Legendre Polynomials: a recurrence relation
Another way to define the Legendre polynomials is via the recurrence
relation
nPn(z) = (2n − 1)zPn−1(z) + (n − 1)Pn−2(z), P0(z) = 1, P1(z) = z.
Using this definition in MAGMA illustrates
assignment :=
sequences [ <expression> : n in range ]
the select expression
recursive definitions using Self
the range expression: [a..b by c]
> L := [ n eq 0 select 1 else n eq 1 select z else
> ((2*n-1)*z*Self(n)-(n-1)*Self(n-1))/n : n in [0..7]];
> L[8];
429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z
Note that MAGMA sequences are indexed from 1, not 0.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 13 / 31
Number systems
The number systems in MAGMA go well beyond the usual provision of
integers, rationals and real numbers. MAGMA has extensive support for
many types of rings, finite fields, and local and global number fields.
To illustrate this, construct the cyclotomic field E = �[ω], where ω3
= 1
and then define three matrices over E.
> E<w> := CyclotomicField(3);
> E;
Cyclotomic Field of order 3 and degree 2
> a := Matrix(2,2,[E| w, 0, w^2, 1]);
> b := Matrix(2,2,[E| 1, -w^2, 0, w]);
> c := Matrix(2,2,[E| 2*w+1, 2*w, w^2, -w]);
It turns out that the group generated by a and b has order 24, but the
group generated by a and c is infinite.
> G1 := sub<GL(2,E) | a, b >;
> G2 := sub<GL(2,E) | a, c >;
> #G1, IsFinite(G2);
24 false
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 14 / 31
Strings
Strings are enclosed in double quotes and the backslash character is used
as an escape. That is, to obtain a double quote, a backslash, a newline or
tab, you would type ", , n or t.
Use IntegerToString to convert an integer to a string.
The expression s * t is the concatenation of strings s and t.
> base := "E";
> for n := 6 to 8 do // or you could use n in [6,7,8]
for> print base*IntegerToString(n);
for> end for;
E6
E7
E8
As in languages such as C++ and Java, // introduces a comment which
extends to the end of the line and /* comment text */ is a comment
which may span several lines.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 15 / 31
Boolean values and relational operators
MAGMA has the usual two Boolean constants true and false and the
usual connectives and, or, xor and not.
But unlike many other programming languages MAGMA uses abbreviations
rather than symbols for its relational operators. For example, to determine
whether x is less than or equal to y you type x le y not x <= y.
MAGMA code meaning
x eq y x = y
x ne y x �= y
x lt y x < y
x le y x ≤ y
x gt y x > y
x ge y x ≥ y
x in A x ∈ A
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 16 / 31
Data structures: sequences and tuples
Only elements of a common structure are allowed in sets or sequences. The
common structure is its universe.
Sequences
> a := [2,3,5,7,11];
> b := [ x^2 : x in a ];
> T := [ x : x in Sym(5) | Order(x) eq 2 ];
> Universe(a);
Integer Ring
A tuple is an element of a Cartesian product.
Tuples
> X := [ < x , Order(x) > : x in Sym(3) ];
> Universe(X):Minimal;
Cartesian Product<GrpPerm: $, Degree 3, Order 2 * 3, Integer Ring>
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 17 / 31
Data structures: sets and indexed sets
As in mathematics, sets do not contain duplicate elements and there is no
preferred order of the elements.
Sets
> V := VectorSpace(GaloisField(4),4);
> G := SpecialUnitaryGroup(4,2);
> e := { V.1^g : g in G };
> #e;
135
An indexed set is a set whose elements are linearly ordered.
Indexed Sets
> A := {@ 3,3,2,1,5,3,5 @};
> print A;
{@ 3,2,1,5 @}
> print A[3];
1
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 18 / 31
Data structures: lists
Lists are ordered collections of objects of any type; that is, a list does not
require its members to belong to a common universe.
Lists
> L := [* 3, G.1 *] where G is SymmetricGroup(4);
> L;
[* 3,
(1, 2, 3, 4),
*]
> Append(~L, "symmetric group");
> L;
[* 3,
(1, 2, 3, 4),
symmetric group
*]
If L is a list or a sequence, Append(~L,x) adds the element x to the end
of L, modifying L in place. The command M := Append(L,x) leaves L
unchanged.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 19 / 31
Data structures: records
Records are a useful and flexible way to store the results of a computation
in fields indexed by field names.
For example, in carrying out a depth-first search to find a directed spanning
forest of a digraph, you might encode the current state of the search as a
record which is updated each time your procedure visits a node.
Records
context := recformat< forest, rho, counter >;
state := rec< context | // n is the number of nodes
forest := [{Integers()|} : i in [1..n]],
rho := [0 : i in [1..n]], // rank of the current node
counter := 0 // number of nodes processed
>;
At the end of the computation state‘forest should hold a sequence of
directed trees.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 20 / 31
Data structures: attributes
An attribute of a category (such as the category GrpMat of matrix groups)
is a value which can be attached to an instance of the category and
accessed via named fields in the way that the fields of a record are accessed.
> G := CoxeterGroup(GrpMat,"H4");
> G‘Order;
14400
You can define your own attributes using the command
AddAttribute(C,F), where C is a category and F is the name of the
attribute (as a string).
An example will be given on the last slide.
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 21 / 31
Data structures: associative arrays
An associative array is a sequence which can be indexed by arbitrary
members of a given universe. In other programming languages this data
structure is called a dictionary, table or hash map.
Associative arrays
> A := AssociativeArray();
> for n in [6,7,8] do
> name := "E"*IntegerToString(n);
> A[name] := CoxeterGroup(name);
> end for;
> Order(A["E6"]);
51840
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 22 / 31
Functions and procedures
In MAGMA there is distinction between functions and procedures : a function
returns (possibly several) values; a procedure does not return a value.
> BinaryOctahedral := function()
> P<x> := PolynomialRing(IntegerRing());
> K<i,q> := NumberField([x^2+1,x^2-2]);
> a := [g/2 : g in [-i-1, -i+1, -i-1, i-1]];
> c := [(1-i)/q,0,0,(1+i)/q];
> return sub< GL(2,K) | a, c >;
> end function;
A procedure can modify an argument, such as A provided it occurs in the
argument list as a reference variable, written ~A.
The following procedure adds m times row i to row j of the matrix A.
> addrow := procedure( ~A, i, j, m )
> n := Ncols(A);
> for k := 1 to n do A[j,k] +:= m*A[i,k]; end for;
> end procedure;
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 23 / 31
Maps
When MAGMA constructs a subgroup of a group it also returns a map from
the subgroup to the group.
> G := Sym(5);
> H,f := sub< G | (1,2)(3,4), (1,2,3,4) >;
> f;
Mapping from: GrpPerm: H to GrpPerm: G
There are several ways to create maps. Here is one way to create the
Frobenius homomorphism of a finite field.
> q := 3;
> F<iota> := GF(q^2);
> sigma := map< F -> F | x :-> x^q >;
> sigma(iota+2);
iota^5
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 24 / 31
Control structures
while
while boolean do statements; end while;
repeat-until
repeat statements; until boolean;
for
for i := a to b by c do statements; end for;
for i in S do statements; end for;
if-then-else
if boolean then statements;
elif boolean then statements;
else statements;
end if;
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 25 / 31
Other useful statements and expressions
case expressions
case statements
select statements
error and error if statements
try — catch e — end try
continue
break
where ... is
exists
forall
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 26 / 31
MAGMA’s type system
(Almost) every object in MAGMA belongs to a category, also known as the
type of the object. In addition, every object has a parent.
> G := Alt(4); // the alternating group on {1,2,3,4}
> G;
Permutation group G acting on a set of cardinality 4
Order = 12 = 2^2 * 3
(1, 2)(3, 4)
(1, 2, 3)
> Type(G);
GrpPerm
> Parent(G);
Power Structure of GrpPerm
> Generic(G);
Symmetric group acting on a set of cardinality 4
Order = 24 = 2^3 * 3
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 27 / 31
Coercion
Suppose that V is a vector space of dimension 3 over the rational numbers.
In MAGMA the elements of V are triples of rational numbers; i.e., row
vectors. However, a triple [2,3,7] represented as a sequence will not be
recognised as an element of V.
> V := VectorSpace(Rationals(),3);
> v := [2,3,7];
> v in V;
> > v in V;
∧
Runtime error in ’in’: Bad argument types
In order to have MAGMA recognise v as an element of V it must be coerced
into V.
> vec := V!v;
> vec in V;
true
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 28 / 31
Styles of programming
MAGMA is an imperative, call by value, lexically scoped, dynamically typed
programming language, with an essentially functional subset.
An imperative language manipulates data directly by assignment statements
and control structures such as loops and if-else constructions. You can do
this in MAGMA.
A functional programming language achieves its goals by composing
functions without side-effects. In MAGMA you can do this too.
Functions are a fundamental part of MAGMA programming and they are
first-class. That is, they can be assigned to variables, stored in data
structures and returned from other functions. They can invoke themselves
recursively and participate in mutual recursion.
MAGMA also has procedures and unlike a function a procedure does not
return a value but it may modify its arguments (provided they are declared
as reference variables).
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 29 / 31
Styles of programming — closures
A closure is a function that has access to local variables from a larger
scope, namely the context in which it is defined.
> add_three := function()
> y := 3;
> return func< x | x + y >;
> end function;
> y := 7;
> add_three()(10);
13
> add_factory := function(y)
> return func< x | x + y >;
> end function;
>
> add3 := add_factory(3);
> add3(10);
13
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 30 / 31
Final example: efficient recursion
The Chebyshev polynomials Tn(z) (of the first kind) may be defined by the
recursion
Tn(z) = 2zTn−1(z) − Tn−2(z), T0(z) = 1, T1(z) = z
> chebyshev := function(n)
> chebyshev_ := procedure(~Z,z,n)
> if not IsDefined(Z‘cheb_poly,n+1) then $$(~Z,z,n-1);
> Append(~Z‘cheb_poly, 2*z*Z‘cheb_poly[n]-Z‘cheb_poly[n-1]);
> end if;
> end procedure;
>
> AddAttribute(Rng,"cheb_poly");
> P<z> := PolynomialRing(Integers());
> P‘cheb_poly := [P| 1, z];
> chebyshev_(~P,z,n);
> return P‘cheb_poly[n+1];
> end function;
> time _ := chebyshev(500);
Time: 0.030
Don Taylor (The University of Sydney) Magma Programming 13 February 2012 31 / 31

More Related Content

Similar to An Introduction to MAGMA

Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
Yahoo Developer Network
 
Design patterns
Design patternsDesign patterns
Design patterns
NYversity
 

Similar to An Introduction to MAGMA (20)

Development of an Interactive Simulation of Steel Cord Manufacturing for Indu...
Development of an Interactive Simulation of Steel Cord Manufacturing for Indu...Development of an Interactive Simulation of Steel Cord Manufacturing for Indu...
Development of an Interactive Simulation of Steel Cord Manufacturing for Indu...
 
Parallel Computing 2007: Overview
Parallel Computing 2007: OverviewParallel Computing 2007: Overview
Parallel Computing 2007: Overview
 
Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
Apache Hadoop India Summit 2011 Keynote talk "Programming Abstractions for Sm...
 
Design patterns
Design patternsDesign patterns
Design patterns
 
A Tool-Supported Approach for Concurrent Execution of Heterogeneous Models (E...
A Tool-Supported Approach for Concurrent Execution of Heterogeneous Models (E...A Tool-Supported Approach for Concurrent Execution of Heterogeneous Models (E...
A Tool-Supported Approach for Concurrent Execution of Heterogeneous Models (E...
 
Ase02 dmp.ppt
Ase02 dmp.pptAse02 dmp.ppt
Ase02 dmp.ppt
 
Unified modeling language
Unified modeling languageUnified modeling language
Unified modeling language
 
Utilization of Timetable Management System to a Medium Scaled University
Utilization of Timetable Management System to a Medium Scaled University Utilization of Timetable Management System to a Medium Scaled University
Utilization of Timetable Management System to a Medium Scaled University
 
Enhancing energy efficient dynamic load balanced clustering protocol using Dy...
Enhancing energy efficient dynamic load balanced clustering protocol using Dy...Enhancing energy efficient dynamic load balanced clustering protocol using Dy...
Enhancing energy efficient dynamic load balanced clustering protocol using Dy...
 
Source Code Summarization
Source Code SummarizationSource Code Summarization
Source Code Summarization
 
Use of Symbolic Computation is Solving Structural Analysis Problems
Use of Symbolic Computation is Solving Structural Analysis ProblemsUse of Symbolic Computation is Solving Structural Analysis Problems
Use of Symbolic Computation is Solving Structural Analysis Problems
 
Efficient Feature Selection for Fault Diagnosis of Aerospace System Using Syn...
Efficient Feature Selection for Fault Diagnosis of Aerospace System Using Syn...Efficient Feature Selection for Fault Diagnosis of Aerospace System Using Syn...
Efficient Feature Selection for Fault Diagnosis of Aerospace System Using Syn...
 
HW/SW Partitioning Approach on Reconfigurable Multimedia System on Chip
HW/SW Partitioning Approach on Reconfigurable Multimedia System on ChipHW/SW Partitioning Approach on Reconfigurable Multimedia System on Chip
HW/SW Partitioning Approach on Reconfigurable Multimedia System on Chip
 
Model executability within the GEMOC Studio
Model executability within the GEMOC StudioModel executability within the GEMOC Studio
Model executability within the GEMOC Studio
 
International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)
 
Mega
MegaMega
Mega
 
STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages
 
Dynamic V&V in Language-Oriented Modeling
Dynamic V&V in Language-Oriented ModelingDynamic V&V in Language-Oriented Modeling
Dynamic V&V in Language-Oriented Modeling
 
Java@intro to programming
Java@intro to programmingJava@intro to programming
Java@intro to programming
 
Reifying the concurrency concern into xDSML specifications
Reifying the concurrency concern into xDSML specificationsReifying the concurrency concern into xDSML specifications
Reifying the concurrency concern into xDSML specifications
 

More from ssuserb83554 (18)

ch3-4
ch3-4ch3-4
ch3-4
 
ch3-3
ch3-3ch3-3
ch3-3
 
ch3-2
ch3-2ch3-2
ch3-2
 
ch3-1
ch3-1ch3-1
ch3-1
 
ch2-3
ch2-3ch2-3
ch2-3
 
ch2-2
ch2-2ch2-2
ch2-2
 
ch2-1
ch2-1ch2-1
ch2-1
 
ch1
ch1ch1
ch1
 
Circular convolution
Circular convolutionCircular convolution
Circular convolution
 
Shannon Switching - Presentation
Shannon Switching - PresentationShannon Switching - Presentation
Shannon Switching - Presentation
 
Rivers and Bridges - Lubeck
Rivers and Bridges - LubeckRivers and Bridges - Lubeck
Rivers and Bridges - Lubeck
 
Rivers and Bridges - Konigsberg-Kalingrad
Rivers and Bridges - Konigsberg-KalingradRivers and Bridges - Konigsberg-Kalingrad
Rivers and Bridges - Konigsberg-Kalingrad
 
Rivers and Bridges - Gdansk
Rivers and Bridges - GdanskRivers and Bridges - Gdansk
Rivers and Bridges - Gdansk
 
Rivers and Bridges - Budapest
Rivers and Bridges - BudapestRivers and Bridges - Budapest
Rivers and Bridges - Budapest
 
Essential of Economic Sustainability
Essential of Economic SustainabilityEssential of Economic Sustainability
Essential of Economic Sustainability
 
Dimensions of Effective Teaching
Dimensions of Effective TeachingDimensions of Effective Teaching
Dimensions of Effective Teaching
 
Lecture 2: Entropy and Mutual Information
Lecture 2: Entropy and Mutual InformationLecture 2: Entropy and Mutual Information
Lecture 2: Entropy and Mutual Information
 
Lecture 1. Introduction
Lecture 1. IntroductionLecture 1. Introduction
Lecture 1. Introduction
 

Recently uploaded

Electricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 studentsElectricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 students
levieagacer
 
Warming the earth and the atmosphere.pptx
Warming the earth and the atmosphere.pptxWarming the earth and the atmosphere.pptx
Warming the earth and the atmosphere.pptx
GlendelCaroz
 
HIV AND INFULENZA VIRUS PPT HIV PPT INFULENZA VIRUS PPT
HIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPTHIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPT

Recently uploaded (20)

A Scientific PowerPoint on Albert Einstein
A Scientific PowerPoint on Albert EinsteinA Scientific PowerPoint on Albert Einstein
A Scientific PowerPoint on Albert Einstein
 
ANATOMY OF DICOT AND MONOCOT LEAVES.pptx
ANATOMY OF DICOT AND MONOCOT LEAVES.pptxANATOMY OF DICOT AND MONOCOT LEAVES.pptx
ANATOMY OF DICOT AND MONOCOT LEAVES.pptx
 
Efficient spin-up of Earth System Models usingsequence acceleration
Efficient spin-up of Earth System Models usingsequence accelerationEfficient spin-up of Earth System Models usingsequence acceleration
Efficient spin-up of Earth System Models usingsequence acceleration
 
NuGOweek 2024 programme final FLYER short.pdf
NuGOweek 2024 programme final FLYER short.pdfNuGOweek 2024 programme final FLYER short.pdf
NuGOweek 2024 programme final FLYER short.pdf
 
Electricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 studentsElectricity and Circuits for Grade 9 students
Electricity and Circuits for Grade 9 students
 
Mining Activity and Investment Opportunity in Myanmar.pptx
Mining Activity and Investment Opportunity in Myanmar.pptxMining Activity and Investment Opportunity in Myanmar.pptx
Mining Activity and Investment Opportunity in Myanmar.pptx
 
Factor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary GlandFactor Causing low production and physiology of mamary Gland
Factor Causing low production and physiology of mamary Gland
 
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY // USES OF ANTIOBIOTICS TYPES OF ANTIB...
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY  // USES OF ANTIOBIOTICS TYPES OF ANTIB...ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY  // USES OF ANTIOBIOTICS TYPES OF ANTIB...
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY // USES OF ANTIOBIOTICS TYPES OF ANTIB...
 
Classification of Kerogen, Perspective on palynofacies in depositional envi...
Classification of Kerogen,  Perspective on palynofacies in depositional  envi...Classification of Kerogen,  Perspective on palynofacies in depositional  envi...
Classification of Kerogen, Perspective on palynofacies in depositional envi...
 
Vital Signs of Animals Presentation By Aftab Ahmed Rahimoon
Vital Signs of Animals Presentation By Aftab Ahmed RahimoonVital Signs of Animals Presentation By Aftab Ahmed Rahimoon
Vital Signs of Animals Presentation By Aftab Ahmed Rahimoon
 
MSCII_ FCT UNIT 5 TOXICOLOGY.pdf
MSCII_              FCT UNIT 5 TOXICOLOGY.pdfMSCII_              FCT UNIT 5 TOXICOLOGY.pdf
MSCII_ FCT UNIT 5 TOXICOLOGY.pdf
 
Costs to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of UgandaCosts to heap leach gold ore tailings in Karamoja region of Uganda
Costs to heap leach gold ore tailings in Karamoja region of Uganda
 
TEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdfTEST BANK for Organic Chemistry 6th Edition.pdf
TEST BANK for Organic Chemistry 6th Edition.pdf
 
PARENTAL CARE IN FISHES.pptx for 5th sem
PARENTAL CARE IN FISHES.pptx for 5th semPARENTAL CARE IN FISHES.pptx for 5th sem
PARENTAL CARE IN FISHES.pptx for 5th sem
 
Introduction and significance of Symbiotic algae
Introduction and significance of  Symbiotic algaeIntroduction and significance of  Symbiotic algae
Introduction and significance of Symbiotic algae
 
Warming the earth and the atmosphere.pptx
Warming the earth and the atmosphere.pptxWarming the earth and the atmosphere.pptx
Warming the earth and the atmosphere.pptx
 
HIV AND INFULENZA VIRUS PPT HIV PPT INFULENZA VIRUS PPT
HIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPTHIV AND INFULENZA VIRUS PPT HIV PPT  INFULENZA VIRUS PPT
HIV AND INFULENZA VIRUS PPT HIV PPT INFULENZA VIRUS PPT
 
NUMERICAL Proof Of TIme Electron Theory.
NUMERICAL Proof Of TIme Electron Theory.NUMERICAL Proof Of TIme Electron Theory.
NUMERICAL Proof Of TIme Electron Theory.
 
VILLAGE ATTACHMENT For rural agriculture PPT.pptx
VILLAGE ATTACHMENT For rural agriculture  PPT.pptxVILLAGE ATTACHMENT For rural agriculture  PPT.pptx
VILLAGE ATTACHMENT For rural agriculture PPT.pptx
 
dkNET Webinar: The 4DN Data Portal - Data, Resources and Tools to Help Elucid...
dkNET Webinar: The 4DN Data Portal - Data, Resources and Tools to Help Elucid...dkNET Webinar: The 4DN Data Portal - Data, Resources and Tools to Help Elucid...
dkNET Webinar: The 4DN Data Portal - Data, Resources and Tools to Help Elucid...
 

An Introduction to MAGMA

  • 1. An Introduction to MAGMA Don Taylor The University of Sydney 13 February 2012 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 1 / 31
  • 2. A little history MAGMA is a programming language for computer algebra, geometry, combinatorics and number theory. It has extensive support for group theoretic computations and can handle permutation groups, matrix groups and finitely-presented groups. A more complete list of applications will be given later. The language was developed by John Cannon and his team at the University of Sydney and was released in December 1993. It replaced CAYLEY, also developed by John Cannon. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 2 / 31
  • 3. MAGMA 2.18 The name ‘MAGMA’ comes from Bourbaki (and Serre) where it is used to denote a set with one or more binary operations without any additional axioms. Thus a magma is the most basic of algebraic structures. Today, in 2012, Version 2.18 of MAGMA is a huge system with more than 5000 pages of documentation in 13 volumes. MAGMA can be used both interactively and as a programming language. The core of MAGMA is programmed in C but a large part of its functionality resides in package files written in the MAGMA user language. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 3 / 31
  • 4. Outline The following topics will be illustrated by examples drawn from a selection of MAGMA packages. 1 Using MAGMA interactively � Using files. � Printing. � The help system. 2 Essential data structures: sets, sequences, records and associative arrays. 3 Functions and procedures, function expressions and maps. 4 MAGMA’s type system and coercion. 5 The MAGMA language and styles of programming. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 4 / 31
  • 5. The MAGMA design The design principles underpinning both the user language and system architecture are based on ideas from universal algebra and category theory. The MAGMA language attempts to approximate the usual mathematical modes of thought and notation as closely as possible. In particular, the principal constructs in the user language are sets, algebraic structures such as groups, rings and fields and morphisms. [The following three slides are from the MAGMA documentation.] Don Taylor (The University of Sydney) Magma Programming 13 February 2012 5 / 31
  • 6. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 7. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 8. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 9. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 10. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 11. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 12. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 13. The MAGMA language Imperative language with standard imperative-style statements and procedures A functional subset providing closures, higher-order functions, and partial evaluation General aggregate data types based on algebraic notions: set, sequence, mapping, magma Universal structure constructors providing a general mechanism for the construction of magmas and mappings Simple but powerful notation for constructing sets and sequences in a natural mathematical style Set and sequence operations which are implemented with a strong emphasis on efficiency Coercion between magmas (including automatic coercion) A package mechanism to support modular program construction Don Taylor (The University of Sydney) Magma Programming 13 February 2012 6 / 31
  • 14. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 15. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 16. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 17. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 18. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 19. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 20. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 21. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 22. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 23. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 24. The MAGMA environment Command completion and interactive line editing History system with recall and editing of previous lines A hierarchical online help facility Packages containing user-defined intrinsics with automatic compilation Environment variables for configuring style of output, etc. Get/set functions and procedures for configuring style, etc. Verbose options for built-in functions Logging of output, redirection of I/O Special file type for fully-featured file I/O Ability to execute system commands from within Magma Input/output pipes for communication with external programs Don Taylor (The University of Sydney) Magma Programming 13 February 2012 7 / 31
  • 25. The main components of MAGMA The MAGMA Language and System Groups Semigroups and Monoids Rings and Fields Commutative Rings Linear Algebra and Module Theory Lattices and Quadratic Forms Algebras Representation Theory Homological Algebra Lie Theory Algebraic Geometry Finite Incidence Geometry Differential Galois Theory Error-correcting Codes Cryptography Mathematical Databases Don Taylor (The University of Sydney) Magma Programming 13 February 2012 8 / 31
  • 26. Interacting with MAGMA To start, simply type magma To stop, type Ctrl-D or > quit; Every instruction to MAGMA must end with a semicolon ( ; ) but don’t type the > sign—this is MAGMA’s prompt character. When developing MAGMA programs it is useful to put the commands in a file. To load the commands from a file named lecture1.m, type > load "lecture1.m"; If you would like MAGMA to pause after each line of input, use > iload "lecture1.m"; Don Taylor (The University of Sydney) Magma Programming 13 February 2012 9 / 31
  • 27. Using MAGMA interactively — Tab completion Suppose that you want to find the first few Legendre polynomials. There are many ways to achieve this in MAGMA. One of the first things to do is to check the documentation to find out if there is already a function which does what you want. Alternatively you can use the MAGMA help system. For example, if you type Legendre at a MAGMA prompt and then press the Tab key you will see the following: > Legendre LegendreEquation LegendrePolynomial LegendreModel LegendreSymbol If you now type P followed by Tab and a semicolon: > LegendrePolynomial; you will see some information about how to use this function. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 10 / 31
  • 28. Using MAGMA interactively — the Help system To get more detailed information, put a question mark before the name of the command: > ?LegendrePolynomial Depending on how MAGMA is installed either a web browser will open showing the online help for the function or MAGMA’s internal help system will provide information about the command. To print the 7th Legendre polynomial simply issue the command > LegendrePolynomial(7); The output is 429/16*$.1^7 - 693/16*$.1^5 + 315/16*$.1^3 - 35/16*$.1 To get more readable output it is possible to assign a more useful name, such as z, to the indeterminate $.1. We shall see how to do this on the next slide. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 11 / 31
  • 29. Legendre Polynomials: Rodrigues’ formula Suppose that you didn’t discover that MAGMA has a built-in function for Legendre polynomials. In that case you can define them yourself using either a direct or recursive formula. For the direct method we use Rodrigue’s formula Pn(z) = 1 2n n! dn dzn (z2 − 1)n . To set this up in MAGMA we need the polynomial ring in the indeterminate z over the rational numbers. > R<z> := PolynomialRing(Rationals()); > P := func< n | Derivative((z^2-1)^n,n)/(2^n*Factorial(n))>; > P(7); 429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z > P(7) eq LegendrePolynomial(7); true Don Taylor (The University of Sydney) Magma Programming 13 February 2012 12 / 31
  • 30. Legendre Polynomials: a recurrence relation Another way to define the Legendre polynomials is via the recurrence relation nPn(z) = (2n − 1)zPn−1(z) + (n − 1)Pn−2(z), P0(z) = 1, P1(z) = z. Using this definition in MAGMA illustrates assignment := sequences [ <expression> : n in range ] the select expression recursive definitions using Self the range expression: [a..b by c] > L := [ n eq 0 select 1 else n eq 1 select z else > ((2*n-1)*z*Self(n)-(n-1)*Self(n-1))/n : n in [0..7]]; > L[8]; 429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z Note that MAGMA sequences are indexed from 1, not 0. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 13 / 31
  • 31. Number systems The number systems in MAGMA go well beyond the usual provision of integers, rationals and real numbers. MAGMA has extensive support for many types of rings, finite fields, and local and global number fields. To illustrate this, construct the cyclotomic field E = �[ω], where ω3 = 1 and then define three matrices over E. > E<w> := CyclotomicField(3); > E; Cyclotomic Field of order 3 and degree 2 > a := Matrix(2,2,[E| w, 0, w^2, 1]); > b := Matrix(2,2,[E| 1, -w^2, 0, w]); > c := Matrix(2,2,[E| 2*w+1, 2*w, w^2, -w]); It turns out that the group generated by a and b has order 24, but the group generated by a and c is infinite. > G1 := sub<GL(2,E) | a, b >; > G2 := sub<GL(2,E) | a, c >; > #G1, IsFinite(G2); 24 false Don Taylor (The University of Sydney) Magma Programming 13 February 2012 14 / 31
  • 32. Strings Strings are enclosed in double quotes and the backslash character is used as an escape. That is, to obtain a double quote, a backslash, a newline or tab, you would type ", , n or t. Use IntegerToString to convert an integer to a string. The expression s * t is the concatenation of strings s and t. > base := "E"; > for n := 6 to 8 do // or you could use n in [6,7,8] for> print base*IntegerToString(n); for> end for; E6 E7 E8 As in languages such as C++ and Java, // introduces a comment which extends to the end of the line and /* comment text */ is a comment which may span several lines. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 15 / 31
  • 33. Boolean values and relational operators MAGMA has the usual two Boolean constants true and false and the usual connectives and, or, xor and not. But unlike many other programming languages MAGMA uses abbreviations rather than symbols for its relational operators. For example, to determine whether x is less than or equal to y you type x le y not x <= y. MAGMA code meaning x eq y x = y x ne y x �= y x lt y x < y x le y x ≤ y x gt y x > y x ge y x ≥ y x in A x ∈ A Don Taylor (The University of Sydney) Magma Programming 13 February 2012 16 / 31
  • 34. Data structures: sequences and tuples Only elements of a common structure are allowed in sets or sequences. The common structure is its universe. Sequences > a := [2,3,5,7,11]; > b := [ x^2 : x in a ]; > T := [ x : x in Sym(5) | Order(x) eq 2 ]; > Universe(a); Integer Ring A tuple is an element of a Cartesian product. Tuples > X := [ < x , Order(x) > : x in Sym(3) ]; > Universe(X):Minimal; Cartesian Product<GrpPerm: $, Degree 3, Order 2 * 3, Integer Ring> Don Taylor (The University of Sydney) Magma Programming 13 February 2012 17 / 31
  • 35. Data structures: sets and indexed sets As in mathematics, sets do not contain duplicate elements and there is no preferred order of the elements. Sets > V := VectorSpace(GaloisField(4),4); > G := SpecialUnitaryGroup(4,2); > e := { V.1^g : g in G }; > #e; 135 An indexed set is a set whose elements are linearly ordered. Indexed Sets > A := {@ 3,3,2,1,5,3,5 @}; > print A; {@ 3,2,1,5 @} > print A[3]; 1 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 18 / 31
  • 36. Data structures: lists Lists are ordered collections of objects of any type; that is, a list does not require its members to belong to a common universe. Lists > L := [* 3, G.1 *] where G is SymmetricGroup(4); > L; [* 3, (1, 2, 3, 4), *] > Append(~L, "symmetric group"); > L; [* 3, (1, 2, 3, 4), symmetric group *] If L is a list or a sequence, Append(~L,x) adds the element x to the end of L, modifying L in place. The command M := Append(L,x) leaves L unchanged. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 19 / 31
  • 37. Data structures: records Records are a useful and flexible way to store the results of a computation in fields indexed by field names. For example, in carrying out a depth-first search to find a directed spanning forest of a digraph, you might encode the current state of the search as a record which is updated each time your procedure visits a node. Records context := recformat< forest, rho, counter >; state := rec< context | // n is the number of nodes forest := [{Integers()|} : i in [1..n]], rho := [0 : i in [1..n]], // rank of the current node counter := 0 // number of nodes processed >; At the end of the computation state‘forest should hold a sequence of directed trees. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 20 / 31
  • 38. Data structures: attributes An attribute of a category (such as the category GrpMat of matrix groups) is a value which can be attached to an instance of the category and accessed via named fields in the way that the fields of a record are accessed. > G := CoxeterGroup(GrpMat,"H4"); > G‘Order; 14400 You can define your own attributes using the command AddAttribute(C,F), where C is a category and F is the name of the attribute (as a string). An example will be given on the last slide. Don Taylor (The University of Sydney) Magma Programming 13 February 2012 21 / 31
  • 39. Data structures: associative arrays An associative array is a sequence which can be indexed by arbitrary members of a given universe. In other programming languages this data structure is called a dictionary, table or hash map. Associative arrays > A := AssociativeArray(); > for n in [6,7,8] do > name := "E"*IntegerToString(n); > A[name] := CoxeterGroup(name); > end for; > Order(A["E6"]); 51840 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 22 / 31
  • 40. Functions and procedures In MAGMA there is distinction between functions and procedures : a function returns (possibly several) values; a procedure does not return a value. > BinaryOctahedral := function() > P<x> := PolynomialRing(IntegerRing()); > K<i,q> := NumberField([x^2+1,x^2-2]); > a := [g/2 : g in [-i-1, -i+1, -i-1, i-1]]; > c := [(1-i)/q,0,0,(1+i)/q]; > return sub< GL(2,K) | a, c >; > end function; A procedure can modify an argument, such as A provided it occurs in the argument list as a reference variable, written ~A. The following procedure adds m times row i to row j of the matrix A. > addrow := procedure( ~A, i, j, m ) > n := Ncols(A); > for k := 1 to n do A[j,k] +:= m*A[i,k]; end for; > end procedure; Don Taylor (The University of Sydney) Magma Programming 13 February 2012 23 / 31
  • 41. Maps When MAGMA constructs a subgroup of a group it also returns a map from the subgroup to the group. > G := Sym(5); > H,f := sub< G | (1,2)(3,4), (1,2,3,4) >; > f; Mapping from: GrpPerm: H to GrpPerm: G There are several ways to create maps. Here is one way to create the Frobenius homomorphism of a finite field. > q := 3; > F<iota> := GF(q^2); > sigma := map< F -> F | x :-> x^q >; > sigma(iota+2); iota^5 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 24 / 31
  • 42. Control structures while while boolean do statements; end while; repeat-until repeat statements; until boolean; for for i := a to b by c do statements; end for; for i in S do statements; end for; if-then-else if boolean then statements; elif boolean then statements; else statements; end if; Don Taylor (The University of Sydney) Magma Programming 13 February 2012 25 / 31
  • 43. Other useful statements and expressions case expressions case statements select statements error and error if statements try — catch e — end try continue break where ... is exists forall Don Taylor (The University of Sydney) Magma Programming 13 February 2012 26 / 31
  • 44. MAGMA’s type system (Almost) every object in MAGMA belongs to a category, also known as the type of the object. In addition, every object has a parent. > G := Alt(4); // the alternating group on {1,2,3,4} > G; Permutation group G acting on a set of cardinality 4 Order = 12 = 2^2 * 3 (1, 2)(3, 4) (1, 2, 3) > Type(G); GrpPerm > Parent(G); Power Structure of GrpPerm > Generic(G); Symmetric group acting on a set of cardinality 4 Order = 24 = 2^3 * 3 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 27 / 31
  • 45. Coercion Suppose that V is a vector space of dimension 3 over the rational numbers. In MAGMA the elements of V are triples of rational numbers; i.e., row vectors. However, a triple [2,3,7] represented as a sequence will not be recognised as an element of V. > V := VectorSpace(Rationals(),3); > v := [2,3,7]; > v in V; > > v in V; ∧ Runtime error in ’in’: Bad argument types In order to have MAGMA recognise v as an element of V it must be coerced into V. > vec := V!v; > vec in V; true Don Taylor (The University of Sydney) Magma Programming 13 February 2012 28 / 31
  • 46. Styles of programming MAGMA is an imperative, call by value, lexically scoped, dynamically typed programming language, with an essentially functional subset. An imperative language manipulates data directly by assignment statements and control structures such as loops and if-else constructions. You can do this in MAGMA. A functional programming language achieves its goals by composing functions without side-effects. In MAGMA you can do this too. Functions are a fundamental part of MAGMA programming and they are first-class. That is, they can be assigned to variables, stored in data structures and returned from other functions. They can invoke themselves recursively and participate in mutual recursion. MAGMA also has procedures and unlike a function a procedure does not return a value but it may modify its arguments (provided they are declared as reference variables). Don Taylor (The University of Sydney) Magma Programming 13 February 2012 29 / 31
  • 47. Styles of programming — closures A closure is a function that has access to local variables from a larger scope, namely the context in which it is defined. > add_three := function() > y := 3; > return func< x | x + y >; > end function; > y := 7; > add_three()(10); 13 > add_factory := function(y) > return func< x | x + y >; > end function; > > add3 := add_factory(3); > add3(10); 13 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 30 / 31
  • 48. Final example: efficient recursion The Chebyshev polynomials Tn(z) (of the first kind) may be defined by the recursion Tn(z) = 2zTn−1(z) − Tn−2(z), T0(z) = 1, T1(z) = z > chebyshev := function(n) > chebyshev_ := procedure(~Z,z,n) > if not IsDefined(Z‘cheb_poly,n+1) then $$(~Z,z,n-1); > Append(~Z‘cheb_poly, 2*z*Z‘cheb_poly[n]-Z‘cheb_poly[n-1]); > end if; > end procedure; > > AddAttribute(Rng,"cheb_poly"); > P<z> := PolynomialRing(Integers()); > P‘cheb_poly := [P| 1, z]; > chebyshev_(~P,z,n); > return P‘cheb_poly[n+1]; > end function; > time _ := chebyshev(500); Time: 0.030 Don Taylor (The University of Sydney) Magma Programming 13 February 2012 31 / 31