<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- %% -->
<!-- %W  xtndxmpl.tex              GAP manual                    Thomas Breuer -->
<!-- %% -->
<!-- %% -->

<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Chapter Label="An Example -- Residue Class Rings">
<Heading>An Example &ndash; Residue Class Rings</Heading>

In this chapter, we give an example how &GAP; can be extended
by new data structures and new functionality.
In order to focus on the issues of the implementation,
the mathematics in the example chosen is trivial.
Namely, we will discuss computations with elements of residue class rings
<M>&ZZ; / n&ZZ;</M>.
<P/>
The first attempt is straightforward
(see Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>),
it deals with the implementation of the necessary arithmetic operations.
Section&nbsp;<Ref Sect="Why Proceed in a Different Way?"/> deals with the question
why it might be useful to use an approach that involves creating a new
data structure and integrating the algorithms dealing with these new
&GAP; objects into the system.
Section&nbsp;<Ref Sect="A Second Attempt to Implement Elements of Residue Class Rings"/>
shows how this can be done in our example,
and Section&nbsp;<Ref Sect="Compatibility of Residue Class Rings with Prime Fields"/>,
the question of further compatibility of the new objects with known
&GAP; objects is discussed.
Finally, Section&nbsp;<Ref Sect="Further Improvements in Implementing Residue Class Rings"/>
gives some hints how to improve the implementation presented before.


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="A First Attempt to Implement Elements of Residue Class Rings">
<Heading>A First Attempt to Implement Elements of Residue Class Rings</Heading>

Suppose we want to do computations with elements of a ring <M>&ZZ; / n&ZZ;</M>,
where <M>n</M> is a positive integer.
<P/>
First we have to decide how to represent the element <M>k + n&ZZ;</M> in &GAP;.
If the modulus <M>n</M> is fixed then we can use the integer <M>k</M>.
More precisely, we can use any integer <M>k'</M>
such that <M>k - k'</M> is a multiple of <M>n</M>.
If different moduli are likely to occur then using a list of the form
<M>[ k, n ]</M>, or a record of the form <C>rec( residue := <A>k</A>, modulus := <A>n</A> )</C>
is more appropriate.
In the following, let us assume the list representation <M>[ k, n ]</M> is
chosen.
Moreover, we decide that the residue <M>k</M> in all such lists satisfies
<M>0 \leq k &lt; n</M>,
i.e., the result of adding two residue classes represented by
<M>[ k_1, n ]</M> and <M>[ k_2, n ]</M> (of course with same modulus <M>n</M>)
will be <M>[ k, n ]</M> with <M>k_1 + k_2</M> congruent to <M>k</M> modulo <M>n</M>
and <M>0 \leq k &lt; n</M>.
<P/>
Now we can implement the arithmetic operations for residue classes.
Note that the result of the <K>mod</K> operator is normalized as required.
The division by a noninvertible residue class results in <K>fail</K>.
<P/>
<Example><![CDATA[
gap> resclass_sum := function( c1, c2 )
>    if c1[2] <> c2[2] then Error( "different moduli" ); fi;
>    return [ ( c1[1] + c2[1] ) mod c1[2], c1[2] ];
> end;;
gap> 
gap> resclass_diff := function( c1, c2 )
>    if c1[2] <> c2[2] then Error( "different moduli" ); fi;
>    return [ ( c1[1] - c2[1] ) mod c1[2], c1[2] ];
> end;;
gap> 
gap> resclass_prod := function( c1, c2 )
>    if c1[2] <> c2[2] then Error( "different moduli" ); fi;
>    return [ ( c1[1] * c2[1] ) mod c1[2], c1[2] ];
> end;;
gap> 
gap> resclass_quo := function( c1, c2 )
>    local quo;
>    if c1[2] <> c2[2] then Error( "different moduli" ); fi;
>    quo:= QuotientMod( c1[1], c2[1], c1[2] );
>    if quo <> fail then
>      quo:= [ quo, c1[2] ];
>    fi;
>    return quo;
> end;;
]]></Example>
<P/>
With these functions, we can in principle compute with residue classes.
<P/>
<Example><![CDATA[
gap> list:= List( [ 0 .. 3 ], k -> [ k, 4 ] );
[ [ 0, 4 ], [ 1, 4 ], [ 2, 4 ], [ 3, 4 ] ]
gap> resclass_sum( list[2], list[4] );
[ 0, 4 ]
gap> resclass_diff( list[1], list[2] );
[ 3, 4 ]
gap> resclass_prod( list[2], list[4] );
[ 3, 4 ]
gap> resclass_prod( list[3], list[4] );
[ 2, 4 ]
gap> List( list, x -> resclass_quo( list[2], x ) );
[ fail, [ 1, 4 ], fail, [ 3, 4 ] ]
]]></Example>

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Why Proceed in a Different Way?">
<Heading>Why Proceed in a Different Way?</Heading>

It depends on the computations we intended to do with residue classes
whether or not the implementation described in the previous section
is satisfactory for us.
<P/>
Probably we are mainly interested in more complex data structures than
the residue classes themselves, for example in matrix algebras or matrix
groups over a ring such as <M>&ZZ; / 4&ZZ;</M>.
For this, we need functions to add, multiply, invert etc.&nbsp;matrices of
residue classes.
Of course this is not a difficult task, but it requires to write
additional &GAP; code.
<P/>
And when we have implemented the arithmetic operations for matrices of
residue classes, we might be interested in domain operations such as
computing the order of a matrix group over <M>&ZZ; / 4&ZZ;</M>,
a Sylow <M>2</M> subgroup, and so on.
The problem is that a residue class represented as a pair <M>[ k, n ]</M>
is not regarded as a group element by &GAP;.
We have not yet discussed how a matrix of residue classes shall be
represented, but if we choose the obvious representation of a list of
lists of our residue classes then also this is not a valid group element
in &GAP;.
Hence we cannot apply the function
<Ref Func="Group" Label="for a list of generators (and an identity element)"/>
to create a group of residue
classes or a group of matrices of residue classes.
This is because &GAP; assumes that group elements can be multiplied via
the infix operator <C>*</C> (equivalently,
via the operation <Ref Oper="\*"/>).
Note that in fact the multiplication of two lists <M>[ k_1, n ]</M>,
<M>[ k_2, n ]</M> is defined, but we have
<M>[ k_1, n ] * [ k_2, n ] = k_1 * k_2 + n * n</M>, the standard scalar
product of two row vectors of same length.
That is, the multiplication with <C>*</C> is not compatible with the function
<C>resclass_prod</C> introduced in the previous section.
Similarly, ring elements are assumed to be added via the infix operator
<C>+</C>; the addition of residue classes is not compatible with the available
addition of row vectors.
<P/>
What we have done in the previous section can be described as
implementation of a <Q>standalone</Q> arithmetic for residue classes.
In order to use the machinery of the &GAP; library for creating higher
level objects such as matrices, polynomials, or domains over residue
class rings,
we have to <Q>integrate</Q> this implementation into the &GAP; library.
The key step will be to create a new kind of &GAP; objects.
This will be done in the following sections;
there we assume that residue classes and residue class rings are not
yet available in &GAP;;
in fact they are available, and their implementation is very close to
what is described here.

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="A Second Attempt to Implement Elements of Residue Class Rings">
<Heading>A Second Attempt to Implement Elements of Residue Class Rings</Heading>

Faced with the problem to implement elements of the rings <M>&ZZ; / n&ZZ;</M>,
we must define the <E>types</E> of these elements as far as is necessary to
distinguish them from other &GAP; objects.
<P/>
As is described in Chapter&nbsp;<Ref Chap="Types of Objects"/>,
the type of an object comprises several aspects of information about this
object;
the <E>family</E> determines the relation of the object to other objects,
the <E>categories</E> determine what operations the object admits,
the <E>representation</E> determines how an object is actually represented,
and the <E>attributes</E> describe knowledge about the object.
<P/>
First of all, we must decide about the <E>family</E> of each residue class.
A natural way to do this is to put the elements of each ring <M>&ZZ; / n&ZZ;</M>
into a family of their own.
This means that for example elements of <M>&ZZ; / 3&ZZ;</M> and <M>&ZZ; / 9&ZZ;</M> lie
in different families.
So the only interesting relation between the families of two residue
classes is equality;
binary arithmetic operations with two residue classes will be admissible
only if their families are equal.
Note that in the naive approach in
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>,
we had to take care of different moduli by a check in each function;
these checks may disappear in the new approach because of our choice
of families.
<P/>
Note that we do not need to tell &GAP; anything about the above
decision concerning the families of the objects that we are going to
implement,
that is, the <E>declaration part</E> (see&nbsp;<Ref Sect="Declaration and Implementation Part"/>)
of the little &GAP; package we are writing contains nothing about the
distribution of the new objects into families.
(The actual construction of a family happens in the function <C>MyZmodnZ</C>
shown below.)
<P/>
Second, we want to describe methods to add or multiply two elements in
<M>&ZZ; / n&ZZ;</M>,
and these methods shall be not applicable to other &GAP; objects.
The natural way to do this is to create a new <E>category</E> in which all
elements of all rings <M>&ZZ; / n&ZZ;</M> lie.
This is done as follows.
<P/>
<Example><![CDATA[
gap> DeclareCategory( "IsMyZmodnZObj", IsScalar );
gap> cat:= CategoryCollections( IsMyZmodnZObj );;
gap> cat:= CategoryCollections( cat );;
gap> cat:= CategoryCollections( cat );;
]]></Example>
<P/>
So all elements in the rings <M>&ZZ; / n&ZZ;</M> will lie in the category
<C>IsMyZmodnZObj</C>, which is a subcategory of
<Ref Filt="IsScalar"/>.
The latter means that one can add, subtract, multiply and divide
two such elements that lie in the same family,
with the obvious restriction that the second operand of a division
must be invertible.
(The name <C>IsMyZmodnZObj</C> is chosen because
<Ref Filt="IsZmodnZObj"/> is already
defined in &GAP;, for an implementation of residue classes that is
very similar to the one developed in this manual chapter.
Using this different name, one can simply enter the &GAP; code of this
chapter into a &GAP; session, either interactively or by reading a file
with this code, and experiment after each step whether the expected
behaviour has been achieved, and what is still missing.)
<P/>
The next lines of &GAP; code above create the categories
<C>CategoryCollections( IsMyZmodnZObj )</C> and two higher levels of collections
categories of this, which will be needed later;
it is important to create these categories before collections of the objects
in <C>IsMyZmodnZObj</C> actually arise.
<P/>
Note that the only difference between <Ref Func="DeclareCategory"/> and
<Ref Func="NewCategory"/>
is that in a call to <Ref Func="DeclareCategory"/>,
a variable corresponding to the
first argument is set to the new category, and this variable is read-only.
The same holds for <Ref Func="DeclareRepresentation"/> and
<Ref Func="NewRepresentation"/> etc.
<P/>
There is no analogue of categories in the implementation in
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>,
since there it was not necessary to distinguish residue classes from
other &GAP; objects.
Note that the functions there assumed that their arguments were residue
classes, and the user was responsible not to call them with other
arguments.
Thus an important aspect of types is to describe arguments of functions
explicitly.
<P/>
Third, we must decide about the <E>representation</E> of our objects.
This is something we know already from
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>,
where we chose a list of length two.
Here we may choose between two essentially different representations for
the new &GAP; objects, namely as <Q>component object</Q> (record-like)
or <Q>positional object</Q> (list-like).
We decide to store the modulus of each residue class in its family,
and to encode the element <M>k + n&ZZ;</M> by the unique residue in the range
<M>[ 0 .. n-1 ]</M> that is congruent to <M>k</M> modulo <M>n</M>,
and the object itself is chosen to be a positional object with this
residue at the first and only position (see&nbsp;<Ref Sect="Positional Objects"/>).
<P/>
<Example><![CDATA[
gap> DeclareRepresentation("IsMyModulusRep", IsPositionalObjectRep, [1]);
]]></Example>
<P/>
The fourth ingredients of a type, <E>attributes</E>, are usually of minor
importance for element objects.
In particular,
we do not need to introduce special attributes for residue classes.
<P/>
Having defined what the new objects shall look like,
we now declare a global function
(see&nbsp;<Ref Sect="Declaration and Implementation Part"/>),
to create an element when family and residue are given.
<P/>
<Example><![CDATA[
gap> DeclareGlobalFunction( "MyZmodnZObj" );
]]></Example>
<P/>
Now we have declared what we need,
and we can start to implement the missing methods resp. functions;
so the following command belongs to the <E>implementation part</E> of our
package (see&nbsp;<Ref Sect="Declaration and Implementation Part"/>).
<P/>
The probably most interesting function is the one to construct a
residue class.
<P/>
<Example><![CDATA[
gap> InstallGlobalFunction( MyZmodnZObj, function( Fam, residue )
>    return Objectify( NewType( Fam, IsMyZmodnZObj and IsMyModulusRep ),
>                      [ residue mod Fam!.modulus ] );
> end );
]]></Example>
<P/>
Note that we normalize <C>residue</C> explicitly using <K>mod</K>;
we assumed that the modulus is stored in <C>Fam</C>,
so we must take care of this below.
If <C>Fam</C> is a family of residue classes, and <C>residue</C> is an integer,
<C>MyZmodnZObj</C> returns the corresponding object in the family <C>Fam</C>,
which lies in the category <C>IsMyZmodnZObj</C> and in the representation
<C>IsMyModulusRep</C>.
<P/>
<C>MyZmodnZObj</C> needs an appropriate family as first argument,
so let us see how to get our hands on this.
Of course we could write a handy function to create such a family
for given modulus, but we choose another way.
In fact we do not really want to call <C>MyZmodnZObj</C> explicitly when we
want to create residue classes.
For example, if we want to enter a matrix of residues then usually
we start with a matrix of corresponding integers,
and it is more elegant to do the conversion via multiplying the matrix
with the identity of the required ring <M>&ZZ; / n&ZZ;</M>;
this is also done for the conversion of integral matrices to
finite field matrices.
(Note that we will have to install a method for this.)
So it is often sufficient to access this identity,
for example via <C>One( MyZmodnZ( <A>n</A> ) )</C>,
where <C>MyZmodnZ</C> returns a domain representing the ring <M>&ZZ; / n&ZZ;</M>
when called with the argument <M>n</M>.
We decide that constructing this ring is a natural place where the
creation of the family can be hidden,
and implement the function.
(Note that the declaration belongs to the declaration part,
and the installation belongs to the implementation part,
see&nbsp;<Ref Sect="Declaration and Implementation Part"/>).
<P/>
<Example><![CDATA[
gap> DeclareGlobalFunction( "MyZmodnZ" );
gap> 
gap> InstallGlobalFunction( MyZmodnZ, function( n )
>    local F, R;
> 
>    if not IsPosInt( n ) then
>      Error( "<n> must be a positive integer" );
>    fi;
> 
>    # Construct the family of element objects of our ring.
>    F:= NewFamily( Concatenation( "MyZmod", String( n ), "Z" ),
>                   IsMyZmodnZObj );
> 
>    # Install the data.
>    F!.modulus:= n;
> 
>    # Make the domain.
>    R:= RingWithOneByGenerators( [ MyZmodnZObj( F, 1 ) ] );
>    SetIsWholeFamily( R, true );
>    SetName( R, Concatenation( "(Integers mod ", String(n), ")" ) );
> 
>    # Return the ring.
>    return R;
> end );
]]></Example>
<P/>
Note that the modulus <C>n</C> is stored in the component <C>modulus</C> of the
family, as is assumed by <C>MyZmodnZ</C>.
Thus it is not necessary to store the modulus in each element.
When storing <C>n</C> with the <C>!.</C> operator as value of the component
<C>modulus</C>, we used that all families are in fact represented as
component objects (see&nbsp;<Ref Sect="Component Objects"/>).
<P/>
We see that we can use <Ref Oper="RingWithOneByGenerators"/>
to construct a ring with one if we have the appropriate generators.
The construction via <Ref Oper="RingWithOneByGenerators"/>
makes sure
that <Ref Filt="IsRingWithOne"/>
(and <Ref Filt="IsRing"/>) is <K>true</K> for each output of
<C>MyZmodnZ</C>.
So the main problem is to create the identity element of the ring,
which in our case suffices to generate the ring.
In order to create this element via <C>MyZmodnZObj</C>,
we have to construct its family first, at each call of <C>MyZmodnZ</C>.
<P/>
Also note that we may enter known information about the ring.
Here we store that it contains the whole family of elements;
this is useful for example when we want to check the membership of an
element in the ring, which can be decided from the type of the element
if the ring contains its whole elements family.
Giving a name to the ring causes that it will be printed
via printing the name.
(By the way:
This name <C>(Integers mod <A>n</A>)</C> looks like a call to
<Ref Oper="\mod"/>
with the arguments <Ref Var="Integers"/> and <A>n</A>;
a construction of the ring via this call seems to be more natural than
by calling <C>MyZmodnZ</C>; later we shall install a
<Ref Oper="\mod"/> method
in order to admit this construction.)
<P/>
Now we can read the above code into &GAP;,
and the following works already.
<P/>
<Example><![CDATA[
gap> R:= MyZmodnZ( 4 );
(Integers mod 4)
gap> IsRing( R );
true
gap> gens:= GeneratorsOfRingWithOne( R );
[ <object> ]
]]></Example>
<P/>
But of course this means just to ask for the information we have
explicitly stored in the ring.
Already the questions whether the ring is finite and how many elements
it has, cannot be answered by &GAP;.
Clearly we know the answers, and we could store them in the ring,
by setting the value of the property <Ref Prop="IsFinite"/>
to <K>true</K> and the value of the attribute
<Ref Attr="Size"/> to <A>n</A>
(the argument of the call to <C>MyZmodnZ</C>).
If we do not want to do so then &GAP; could only try to find out the number
of elements of the ring via forming the closure of the generators
under addition and multiplication,
but up to now, &GAP; does not know how to add or multiply two
elements of our ring.
<P/>
So we must install some methods for arithmetic and other
operations if the elements are to behave as we want.
<P/>
We start with a method for showing elements nicely on the screen.
There are different operations for this purpose.
One of them is <Ref Oper="PrintObj"/>,
which is called for each argument in an explicit call to
<Ref Func="Print"/>.
Another one is <Ref Oper="ViewObj"/>,
which is called in the read-eval-print loop for each object.
<Ref Oper="ViewObj"/> shall produce short and human readable
information about the object in question,
whereas <Ref Oper="PrintObj"/> shall produce information that
may be longer and is (if reasonable) readable by &GAP;.
We cannot satisfy the latter requirement for a
<Ref Oper="PrintObj"/> method
because there is no way to make a family &GAP; readable.
So we decide to display the expression <C>( k mod n )</C> for an object
that is given by the residue <C>k</C> and the modulus <C>n</C>,
which would be fine as a <Ref Oper="ViewObj"/> method.
Since the default for <Ref Oper="ViewObj"/> is to call
<Ref Oper="PrintObj"/>,
and since no other <Ref Oper="ViewObj"/> method is applicable
to our elements,
we need only a <Ref Oper="PrintObj"/> method.
<P/>
<Example><![CDATA[
gap> InstallMethod( PrintObj,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj and IsMyModulusRep ],
>    function( x )
>    Print( "( ", x![1], " mod ", FamilyObj(x)!.modulus, " )" );
>    end );
]]></Example>
<P/>
So we installed a method for the operation
<Ref Oper="PrintObj"/> (first argument),
and we gave it a suitable information message (second argument),
see&nbsp;<Ref Sect="ApplicableMethod"/> and&nbsp;<Ref Sect="Tracing Methods"/> for applications of
this information string.
The third argument tells &GAP; that the method is applicable for
objects that lie in the category <C>IsMyZmodnZObj</C> and in the representation
<C>IsMyModulusRep</C>.
and the fourth argument is the method itself.
More details about <Ref Func="InstallMethod"/> can be found
in&nbsp;<Ref Sect="Method Installation"/>.
<P/>
Note that the requirement <C>IsMyModulusRep</C> for the argument <C>x</C> allows us
to access the residue as <C>x![1]</C>.
Since the family of <C>x</C> has the component <C>modulus</C> bound if it is
constructed by <C>MyZmodnZ</C>, we may access this component.
We check whether the method installation has some effect.
<P/>
<Example><![CDATA[
gap> gens;
[ ( 1 mod 4 ) ]
]]></Example>
<P/>
Next we install methods for the comparison operations.
Note that we can assume that the residues in the representation chosen
are normalized.
<P/>
<Example><![CDATA[
gap> InstallMethod( \=,
>    "for two elements in Z/nZ (ModulusRep)",
>    IsIdenticalObj,
>    [IsMyZmodnZObj and IsMyModulusRep, IsMyZmodnZObj and IsMyModulusRep],
>    function( x, y ) return x![1] = y![1]; end );
gap> 
gap> InstallMethod( \<,
>    "for two elements in Z/nZ (ModulusRep)",
>    IsIdenticalObj,
>    [IsMyZmodnZObj and IsMyModulusRep, IsMyZmodnZObj and IsMyModulusRep],
>    function( x, y ) return x![1] < y![1]; end );
]]></Example>
<P/>
The third argument used in these installations specifies the required
relation between the families of the arguments
(see&nbsp;<Ref Sect="Families"/>).
This argument of a method installation, if present, is a function that shall
be applied to the families of the arguments.
<Ref Func="IsIdenticalObj"/> means that the methods are
applicable only if both arguments lie in the same family.
(In installations for unary methods, obviously no relation is required,
so this argument is left out there.)
<P/>
Up to now, we see no advantage of the new approach over the one in
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>.
For a residue class represented as <C>[ <A>k</A>, <A>n</A> ]</C>, the way it is printed
on the screen is sufficient, and equality and comparison of lists are
good enough to define equality and comparison of residue classes if needed.
But this is not the case in other situations.
For example, if we would have decided that the residue <A>k</A> need not be
normalized then we would have needed functions in
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>
that compute whether two residue classes are equal, and which of two
residue classes is regarded as larger than another.
Note that we are free to define what <Q>larger</Q> means for objects that
are newly introduced.
<P/>
Next we install methods for the arithmetic operations,
first for the additive structure.
<P/>
<Example><![CDATA[
gap> InstallMethod( \+,
>    "for two elements in Z/nZ (ModulusRep)",
>    IsIdenticalObj,
>    [IsMyZmodnZObj and IsMyModulusRep, IsMyZmodnZObj and IsMyModulusRep],
>    function( x, y )
>    return MyZmodnZObj( FamilyObj( x ), x![1] + y![1] );
>    end );
gap> 
gap> InstallMethod( ZeroOp,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj ],
>    x -> MyZmodnZObj( FamilyObj( x ), 0 ) );
gap> 
gap> InstallMethod( AdditiveInverseOp,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj and IsMyModulusRep ],
>    x -> MyZmodnZObj( FamilyObj( x ), AdditiveInverse( x![1] ) ) );
]]></Example>
<P/>
Here the new approach starts to pay off.
The method for the operation <Ref Oper="\+"/> allows us
to use the infix operator <C>+</C> for residue classes.
The method for <Ref Oper="ZeroOp"/> is used when we call
this operation or the attribute <Ref Attr="Zero"/> explicitly,
and <Ref Oper="ZeroOp"/> it is also used when we ask for
<C>0 * <A>rescl</A></C>, where <A>rescl</A> is a residue class.
<P/>
(Note that <Ref Attr="Zero"/> and
<Ref Oper="ZeroOp"/> are distinguished
because <C>0 * <A>obj</A></C> is guaranteed to return a <E>mutable</E> result
whenever a mutable version of this result exists in &GAP;
&ndash;for example if <A>obj</A> is a matrix&ndash;
whereas <Ref Attr="Zero"/> is an attribute and therefore
returns <E>immutable</E> results;
for our example there is no difference since the residue classes are
always immutable,
nevertheless we have to install the method for
<Ref Oper="ZeroOp"/>.
The same holds for <Ref Attr="AdditiveInverse"/>,
<Ref Attr="One"/>, and <Ref Attr="Inverse"/>.)
<P/>
Similarly, <Ref Oper="AdditiveInverseOp"/> can be either
called directly or via the unary <C>-</C> operator;
so we can compute the additive inverse of the
residue class <A>rescl</A> as <C>-<A>rescl</A></C>.
<P/>
It is not necessary to install methods for subtraction,
since this is handled via addition of the additive inverse of
the second argument if no other method is installed.
<P/>
Let us try what we can do with the methods that are available now.
<P/>
<Example><![CDATA[
gap> x:= gens[1];  y:= x + x;
( 1 mod 4 )
( 2 mod 4 )
gap> 0 * x;  -x;
( 0 mod 4 )
( 3 mod 4 )
gap> y = -y;  x = y;  x < y;  -x < y;
true
false
true
false
]]></Example>
<P/>
We might want to admit the addition of integers and elements in
rings <M>&ZZ; / n&ZZ;</M>, where an integer is implicitly identified
with its residue modulo <M>n</M>.
To achieve this, we install methods to add an integer to an object in
<C>IsMyZmodnZObj</C> from the left and from the right.
<P/>
<Example><![CDATA[
gap> InstallMethod( \+,
>    "for element in Z/nZ (ModulusRep) and integer",
>    [ IsMyZmodnZObj and IsMyModulusRep, IsInt ],
>    function( x, y )
>    return MyZmodnZObj( FamilyObj( x ), x![1] + y );
>    end );
gap> 
gap> InstallMethod( \+,
>    "for integer and element in Z/nZ (ModulusRep)",
>    [ IsInt, IsMyZmodnZObj and IsMyModulusRep ],
>    function( x, y )
>    return MyZmodnZObj( FamilyObj( y ), x + y![1] );
>    end );
]]></Example>
<P/>
Now we can do also the following.
<P/>
<Example><![CDATA[
gap> 2 + x;  7 - x;  y - 2;
( 3 mod 4 )
( 2 mod 4 )
( 0 mod 4 )
]]></Example>
<P/>
Similarly we install the methods dealing with the multiplicative
structure.
We need methods to multiply two of our objects,
and to compute identity and inverse.
The operation <Ref Oper="OneOp"/> is called when we ask for
<C><A>rescl</A>^0</C>,
and <Ref Oper="InverseOp"/> is called when we ask for
<C><A>rescl</A>^-1</C>.
Note that the method for <Ref Oper="InverseOp"/> returns
<K>fail</K> if the argument is not invertible.
<P/>
<Example><![CDATA[
gap> InstallMethod( \*,
>    "for two elements in Z/nZ (ModulusRep)",
>    IsIdenticalObj,
>    [IsMyZmodnZObj and IsMyModulusRep, IsMyZmodnZObj and IsMyModulusRep],
>    function( x, y )
>    return MyZmodnZObj( FamilyObj( x ), x![1] * y![1] );
>    end );
gap> 
gap> InstallMethod( OneOp,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj ],
>    elm -> MyZmodnZObj( FamilyObj( elm ), 1 ) );
gap> 
gap> InstallMethod( InverseOp,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj and IsMyModulusRep ],
>    function( elm )
>    local residue;
>    residue:= QuotientMod( 1, elm![1], FamilyObj( elm )!.modulus );
>    if residue <> fail then
>      residue:= MyZmodnZObj( FamilyObj( elm ), residue );
>    fi;
>    return residue;
>    end );
]]></Example>
<P/>
To be able to multiply our objects with integers,
we need not (but we may, and we should if we are going for efficiency)
install special methods.
This is because in general, &GAP; interprets the multiplication
of an integer and an additive object as abbreviation of successive
additions, and there is one generic method for such a multiplication
that uses only additions and &ndash;in the case of a negative integer&ndash;
taking the additive inverse.
Analogously, there is a generic method for powering by integers
that uses only multiplications and taking the multiplicative inverse.
<P/>
Note that we could also interpret the multiplication with an integer
as a shorthand for the multiplication with the corresponding residue
class.
We are lucky that this interpretation is compatible with the one that
is already available.
If this would not be the case then of course we would get into trouble
by installing a concurrent multiplication that computes something
different from the multiplication that is already defined,
since &GAP; does not guarantee which of the applicable methods is
actually chosen (see&nbsp;<Ref Sect="Applicable Methods and Method Selection"/>).
<P/>
Now we have implemented methods for the arithmetic operations for our
elements, and the following calculations work.
<P/>
<Example><![CDATA[
gap> y:= 2 * x;  z:= (-5) * x;
( 2 mod 4 )
( 3 mod 4 )
gap> y * z;  y * y;
( 2 mod 4 )
( 0 mod 4 )
gap> y^-1;  y^0;
fail
( 1 mod 4 )
gap> z^-1;
( 3 mod 4 )
]]></Example>
<P/>
There are some other operations in &GAP; that we may want to accept
our elements as arguments.
An example is the operation <Ref Attr="Int"/> that returns,
e.g.,
the integral part of a rational number or the integer corresponding to
an element in a finite prime field.
For our objects, we may define that <Ref Attr="Int"/> returns
the normalized residue.
<P/>
Note that we <E>define</E> this behaviour for elements
but we <E>implement</E> it for objects in the representation <C>IsMyModulusRep</C>.
This means that if someone implements another representation of
residue classes then this person must be careful to implement
<Ref Attr="Int"/>
methods for objects in this new representation compatibly with our
definition, i.e., such that the result is independent of the representation.
<P/>
<Example><![CDATA[
gap> InstallMethod( Int,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObj and IsMyModulusRep ],
>    z -> z![1] );
]]></Example>
<P/>
Another example of an operation for which we might want to install
a method is <Ref Oper="\mod"/>.
We make the ring print itself as
<Ref Var="Integers"/> mod the modulus,
and then it is reasonable to allow a construction this way,
which makes the <Ref Oper="PrintObj"/> output of the ring
&GAP; readable.
<P/>
<Example><![CDATA[
gap> InstallMethod( PrintObj,
>    "for full collection Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObj ) and IsWholeFamily ],
>    function( R )
>    Print( "(Integers mod ",
>           ElementsFamily( FamilyObj(R) )!.modulus, ")" );
>    end );
gap> 
gap> InstallMethod( \mod,
>    "for `Integers', and a positive integer",
>    [ IsIntegers, IsPosRat and IsInt ],
>    function( Integers, n ) return MyZmodnZ( n ); end );
]]></Example>
<P/>
Let us try this.
<P/>
<Example><![CDATA[
gap> Int( y );
2
gap> Integers mod 1789;
(Integers mod 1789)
]]></Example>
<P/>
Probably it is not necessary to emphasize that with the approach of
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>,
installing methods for existing operations is usually not possible or
at least not recommended.
For example, installing the function <C>resclass_sum</C> defined in
Section&nbsp;<Ref Sect="A First Attempt to Implement Elements of Residue Class Rings"/>
as a <Ref Oper="\+"/> method for adding two lists of length two
(with integer entries) would not be compatible with the general
definition of the addition of two lists of same length.
Installing a method for the operation <Ref Attr="Int"/>
that takes a list
<C>[ <A>k</A>, <A>n</A> ]</C> and returns <A>k</A> would in principle be possible,
since there is no <Ref Attr="Int"/> method for lists yet,
but it is not sensible to do so because one can think of other
interpretations of such a list where different
<Ref Attr="Int"/> methods could
be installed with the same right.
<P/>
As mentioned in Section&nbsp;<Ref Sect="Why Proceed in a Different Way?"/>,
one advantage of the new approach is that with the implementation
we have up to now, automatically also matrices of residue classes
can be treated.
<P/>
<Example><![CDATA[
gap> r:= Integers mod 16;
(Integers mod 16)
gap> x:= One( r );
( 1 mod 16 )
gap> mat:= IdentityMat( 2 ) * x;
[ [ ( 1 mod 16 ), ( 0 mod 16 ) ], [ ( 0 mod 16 ), ( 1 mod 16 ) ] ]
gap> mat[1][2]:= x;;
gap> mat;
[ [ ( 1 mod 16 ), ( 1 mod 16 ) ], [ ( 0 mod 16 ), ( 1 mod 16 ) ] ]
gap> Order( mat );
16
gap> mat + mat;
[ [ ( 2 mod 16 ), ( 2 mod 16 ) ], [ ( 0 mod 16 ), ( 2 mod 16 ) ] ]
gap> last^4;
[ [ ( 0 mod 16 ), ( 0 mod 16 ) ], [ ( 0 mod 16 ), ( 0 mod 16 ) ] ]
]]></Example>
<P/>
Such matrices, if they are invertible, are valid as group elements.
One technical problem is that the default algorithm for inverting matrices
may give up since Gaussian elimination need not be successful over rings
containing zero divisors.
Therefore we install a simpleminded inversion method that inverts an integer
matrix.
<P/>
<Example><![CDATA[
gap> InstallMethod( InverseOp,
>    "for an ordinary matrix over a ring Z/nZ",
>    [ IsMatrix and IsOrdinaryMatrix
>      and CategoryCollections( CategoryCollections( IsMyZmodnZObj ) ) ],
>    function( mat )
>    local one, modulus;
> 
>    one:= One( mat[1][1] );
>    modulus:= FamilyObj( one )!.modulus;
>    mat:= InverseOp( List( mat, row -> List( row, Int ) ) );
>    if mat <> fail then
>      mat:= ( mat mod modulus ) * one;
>    fi;
>    if not IsMatrix( mat ) then
>      mat:= fail;
>    fi;
>    return mat;
>    end );
]]></Example>
<P/>
Additionally we install a method for finding a domain that contains the
matrix entries; this is used by some &GAP; library functions.
<P/>
<Example><![CDATA[
gap> InstallMethod( DefaultFieldOfMatrixGroup,
>     "for a matrix group over a ring Z/nZ",
>     [ IsMatrixGroup and CategoryCollections( CategoryCollections(
>           CategoryCollections( IsMyZmodnZObj ) ) ) ],
>     G -> RingWithOneByGenerators([ One( Representative( G )[1][1] ) ]));
]]></Example>
<P/>
Now we can deal with matrix groups over residue class rings.
<P/>
<Example><![CDATA[
gap> mat2:= IdentityMat( 2 ) * x;;
gap> mat2[2][1]:= x;;
gap> g:= Group( mat, mat2 );;
gap> Size( g );
3072
gap> Factors( last );
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3 ]
gap> syl3:= SylowSubgroup( g, 3 );;
gap> gens:= GeneratorsOfGroup( syl3 );
[ [ [ ( 1 mod 16 ), ( 7 mod 16 ) ], [ ( 11 mod 16 ), ( 14 mod 16 ) ]
     ] ]
gap> Order( gens[1] );
3
]]></Example>
<P/>
It should be noted that this way more involved methods for matrix groups
may not be available.
For example, many questions about a finite matrix group can be delegated
to an isomorphic permutation group via a so-called <Q>nice monomorphism</Q>;
this can be controlled by the filter
<Ref Prop="IsHandledByNiceMonomorphism"/>.
<P/>
By the way, also groups of (invertible) residue classes can be formed,
but this may be of minor interest.
<Example><![CDATA[
gap> g:= Group( x );;  Size( g );
#I  default `IsGeneratorsOfMagmaWithInverses' method returns `true' for
[ ( 1 mod 16 ) ]
1
gap> g:= Group( 3*x );;  Size( g );
#I  default `IsGeneratorsOfMagmaWithInverses' method returns `true' for
[ ( 3 mod 16 ) ]
4
]]></Example>
<P/>
(The messages above tell that &GAP; does not know a method for deciding
whether the given elements are valid group elements.
We could add an appropriate <C>IsGeneratorsOfMagmaWithInverses</C> method if
we would want.)
<P/>
Having done enough for the elements,
we may install some more methods for the rings
if we want to use them as arguments.
These rings are finite,
and there are many generic methods that will work if they are able
to compute the list of elements of the ring,
so we install a method for this.
<P/>
<Example><![CDATA[
gap> InstallMethod( Enumerator,
>    "for full collection Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObj ) and IsWholeFamily ],
>    function( R )
>    local F;
>    F:= ElementsFamily( FamilyObj(R) );
>    return List( [ 0 .. Size( R ) - 1 ], x -> MyZmodnZObj( F, x ) );
>    end );
]]></Example>
<P/>
Note that this method is applicable only to full rings <M>&ZZ; / n&ZZ;</M>,
for proper subrings it would return a wrong result.
Furthermore, it is not required that the argument is a ring;
in fact this method is applicable also to the additive group
formed by all elements in the family,
provided that it knows to contain the whole family.
<P/>
Analogously, we install methods to compute the size,
a random element, and the units of full rings <M>&ZZ; / n&ZZ;</M>.
<P/>
<Example><![CDATA[
gap> InstallMethod( Random,
>    "for full collection Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObj ) and IsWholeFamily ],
>    R -> MyZmodnZObj( ElementsFamily( FamilyObj(R) ),
>                    Random( 0, Size( R ) - 1 ) ) );
gap> 
gap> InstallMethod( Size,
>    "for full ring Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObj ) and IsWholeFamily ],
>    R -> ElementsFamily( FamilyObj(R) )!.modulus );
gap> 
gap> InstallMethod( Units,
>    "for full ring Z/nZ",
>    [     CategoryCollections( IsMyZmodnZObj )
>      and IsWholeFamily and IsRing ],
>    function( R )
>    local F;
>    F:= ElementsFamily( FamilyObj( R ) );
>    return List( PrimeResidues( Size(R) ), x -> MyZmodnZObj( F, x ) );
>    end );
]]></Example>
<P/>
The <Ref Attr="Units"/> method has the disadvantage
that the result is returned as a list
(in fact this list is also strictly sorted).
We could improve the implementation by returning the units as a group;
if we do not want to take the full list of elements as generators,
we can use the function <Ref Func="GeneratorsPrimeResidues"/>.
<P/>
<Example><![CDATA[
gap> InstallMethod( Units,
>    "for full ring Z/nZ",
>    [     CategoryCollections( IsMyZmodnZObj )
>      and IsWholeFamily and IsRing ],
>    function( R )
>    local G, gens;
> 
>    gens:= GeneratorsPrimeResidues( Size( R ) ).generators;
>    if not IsEmpty( gens ) and gens[ 1 ] = 1 then
>      gens:= gens{ [ 2 .. Length( gens ) ] };
>    fi;
>    gens:= Flat( gens ) * One( R );
>    return GroupByGenerators( gens, One( R ) );
>    end );
]]></Example>
<P/>
Each ring <M>&ZZ; / n&ZZ;</M> is finite,
and we could install a method that returns <K>true</K> when
<Ref Prop="IsFinite"/> is
called with <M>&ZZ; / n&ZZ;</M> as argument.
But we can do this more elegantly via installing a <E>logical implication</E>.
<P/>
<Example><![CDATA[
gap> InstallTrueMethod( IsFinite,
>    CategoryCollections( IsMyZmodnZObj ) and IsDomain );
]]></Example>
<P/>
In effect, every domain that consists of elements in <C>IsMyZmodnZObj</C>
will automatically store that it is finite,
even if <Ref Prop="IsFinite"/> is not called for it.

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Compatibility of Residue Class Rings with Prime Fields">
<Heading>Compatibility of Residue Class Rings with Prime Fields</Heading>

The above implementation of residue classes and residue class rings
has at least two disadvantages.
First, if <M>p</M> is a prime then the ring <M>&ZZ; / p&ZZ;</M> is in fact a field,
but the return values of <C>MyZmodnZ</C> are never regarded as fields because
they are not in the category
<Ref Filt="IsMagmaWithInversesIfNonzero"/>.
Second, and this makes the example really interesting,
there are already elements of finite prime fields implemented in &GAP;,
and we may want to identify them with elements in <M>&ZZ; / p&ZZ;</M>.
<P/>
To be more precise,
elements of finite fields in &GAP; lie in the category
<Ref Filt="IsFFE"/>,
and there is already a representation,
<Ref Filt="IsInternalRep"/>, of these elements
via discrete logarithms.
The aim of this section is to make <C>IsMyModulusRep</C> an alternative
representation of elements in finite prime fields.
<P/>
Note that this is only one step towards the desired compatibility.
Namely, after having a second representation of elements in finite
prime fields, we may wish that the function
<Ref Func="GF" Label="for field size"/>
(which is the usual
function to create finite fields in &GAP;) is able to return
<C>MyZmodnZ( <A>p</A> )</C> when <C>GF( <A>p</A> )</C> is called for a prime <A>p</A>.
Moreover, then we have to decide about a default representation of
elements in <C>GF( <A>p</A> )</C> for primes <A>p</A> for which both representations are
available.
Of course we can force the new representation by explicitly calling
<C>MyZmodnZ</C> and <C>MyZmodnZObj</C> whenever we want, but it is not a priori
clear in which situation which representation is preferable.
<P/>
The same questions will occur when we want to implement a new
representation for non-prime fields.
The steps of this implementation will be the same as described in this
chapter,
and we will have to achieve compatibility with both the internal
representation of elements in small finite fields and the representation
<C>IsMyModulusRep</C> of elements in arbitrary prime fields.
<P/>
But let us now turn back to the task of this section.
We first adjust the setup of the declaration part of the previous section,
and then repeat the installations with suitable modifications.
<P/>
(We should start a new &GAP; session for that, otherwise &GAP; will
complain that the objects to be declared are already bound;
additionally, the methods installed above may be not compatible with
the ones we want.)
<P/>
<Log><![CDATA[
gap> DeclareCategory( "IsMyZmodnZObj", IsScalar );
gap> 
gap> DeclareCategory( "IsMyZmodnZObjNonprime", IsMyZmodnZObj );
gap> 
gap> DeclareSynonym( "IsMyZmodpZObj", IsMyZmodnZObj and IsFFE );
gap> 
gap> DeclareRepresentation( "IsMyModulusRep", IsPositionalObjectRep, [ 1 ] );
gap> 
gap> DeclareGlobalFunction( "MyZmodnZObj" );
gap> 
gap> DeclareGlobalFunction( "MyZmodnZ" );
]]></Log>
<P/>
As in the previous section,
all (newly introduced) elements of rings <M>&ZZ; / n&ZZ;</M> lie in the category
<C>IsMyZmodnZObj</C>.
But now we introduce two subcategories, namely <C>IsMyZmodnZObjNonprime</C>
for all elements in rings <M>&ZZ; / n&ZZ;</M> where <M>n</M> is not a prime,
and <C>IsMyZmodpZObj</C> for elements in finite prime fields.
All objects in the latter are automatically known to lie in the
category <Ref Filt="IsFFE"/> of finite field elements.
<P/>
It would be reasonable if also those internally represented elements
in the category <Ref Filt="IsFFE"/> that do in fact lie
in a prime field
would also  lie in the category <C>IsMyZmodnZObj</C> (and thus in fact in
<C>IsMyZmodpZObj</C>).
But this cannot be achieved because internally represented finite field
elements do in general not store whether they lie in a prime field.
<P/>
As for the implementation part,
again let us start with the definitions of <C>MyZmodnZObj</C> and <C>MyZmodnZ</C>.
<P/>
<Log><![CDATA[
gap> InstallGlobalFunction( MyZmodnZObj, function( Fam, residue )
>    if IsFFEFamily( Fam ) then
>      return Objectify( NewType( Fam, IsMyZmodpZObj
>                                  and IsMyModulusRep ),
>                    [ residue mod Characteristic( Fam ) ] );
>    else
>      return Objectify( NewType( Fam, IsMyZmodnZObjNonprime
>                                  and IsMyModulusRep ),
>                    [ residue mod Fam!.modulus ] );
>    fi;
> end );

gap> InstallGlobalFunction( MyZmodnZ, function( n )
>    local F, R;
> 
>    if not ( IsInt( n ) and IsPosRat( n ) ) then
>      Error( "<n> must be a positive integer" );
>    elif IsPrimeInt( n ) then
>      # Construct the family of element objects of our field.
>      F:= FFEFamily( n );
>      # Make the domain.
>      R:= FieldOverItselfByGenerators( [ MyZmodnZObj( F, 1 ) ] );
>      SetIsPrimeField( R, true );
>    else
>      # Construct the family of element objects of our ring.
>      F:= NewFamily( Concatenation( "MyZmod", String( n ), "Z" ),
>                     IsMyZmodnZObjNonprime );
>      # Install the data.
>      F!.modulus:= n;
>      # Make the domain.
>      R:= RingWithOneByGenerators( [ MyZmodnZObj( F, 1 ) ] );
>      SetIsWholeFamily( R, true );
>      SetName( R, Concatenation( "(Integers mod ",String(n),")" ) );
>    fi;
> 
>    # Return the ring resp. field.
>    return R;
> end );
]]></Log>
<P/>
Note that the result of <C>MyZmodnZ</C> with a prime as argument is a field that
does not contain the whole family of its elements, since all finite field
elements of a fixed characteristic lie in the same family.
Further note that we cannot expect a family of finite field elements
to have a component <C>modulus</C>,
so we use <Ref Attr="Characteristic"/> to get the modulus.
Requiring that <C>Fam!.modulus</C> works also if <C>Fam</C> is a family of
finite field elements would violate the rule
that an extension of &GAP; should not force changes in existing code,
in this case code dealing with families of finite field elements.
<P/>
<Log><![CDATA[
gap> InstallMethod( PrintObj,
>    "for element in Z/nZ (ModulusRep)",
>    [ IsMyZmodnZObjNonprime and IsMyModulusRep ],
>    function( x )
>    Print( "( ", x![1], " mod ", FamilyObj(x)!.modulus, " )" );
>    end );
gap> 
gap> InstallMethod( PrintObj,
>    "for element in Z/pZ (ModulusRep)",
>    [ IsMyZmodpZObj and IsMyModulusRep ],
>    function( x )
>    Print( "( ", x![1], " mod ", Characteristic(x), " )" );
>    end );
gap> 
gap> InstallMethod( \=,
>    "for two elements in Z/nZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsMyZmodnZObj and IsMyModulusRep,
>      IsMyZmodnZObj and IsMyModulusRep ],
>    function( x, y ) return x![1] = y![1]; end );
]]></Log>
<P/>
The above method to check equality is independent of whether the
arguments have a prime or nonprime modulus,
so we installed it for arguments in <C>IsMyZmodnZObj</C>.
Now we install also methods to compare objects in <C>IsMyZmodpZObj</C>
with the <Q>old</Q> finite field elements.
<P/>
<Log><![CDATA[
gap> InstallMethod( \=,
>    "for element in Z/pZ (ModulusRep) and internal FFE",
>    IsIdenticalObj,
>    [ IsMyZmodpZObj and IsMyModulusRep, IsFFE and IsInternalRep ],
>    function( x, y )
>    return DegreeFFE( y ) = 1 and x![1] = IntFFE( y );
>    end );
gap> 
gap> InstallMethod( \=,
>    "for internal FFE and element in Z/pZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsFFE and IsInternalRep, IsMyZmodpZObj and IsMyModulusRep ],
>    function( x, y )
>    return DegreeFFE( x ) = 1 and IntFFE( x ) = y![1];
>    end );
]]></Log>
<P/>
The situation with the operation <C>&lt;</C> is more difficult.
Of course we are free to define the comparison of objects in
<C>IsMyZmodnZObjNonprime</C>,
but for the finite field elements, the comparison must be compatible
with the predefined comparison of the <Q>old</Q> finite field elements.
The definition of the <C>&lt;</C> comparison of internally represented
finite field elements can be found
in Chapter&nbsp;<Ref Chap="Finite Fields"/>.
In situations where the documentation does not provide the required
information, one has to look it up in the &GAP; code;
for example, the comparison in our case can be found in the
appropriate source code file of the &GAP; kernel.
<P/>
<Log><![CDATA[
gap> InstallMethod( \<,
>    "for two elements in Z/nZ (ModulusRep, nonprime)",
>    IsIdenticalObj,
>    [ IsMyZmodnZObjNonprime and IsMyModulusRep,
>      IsMyZmodnZObjNonprime and IsMyModulusRep ],
>    function( x, y ) return x![1] < y![1]; end );
gap> 
gap> InstallMethod( \<,
>    "for two elements in Z/pZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsMyZmodpZObj and IsMyModulusRep,
>      IsMyZmodpZObj and IsMyModulusRep ],
>    function( x, y )
>    local p, r;      # characteristic and primitive root
>    if x![1] = 0 then
>      return y![1] <> 0;
>    elif y![1] = 0 then
>      return false;
>    else
>      p:= Characteristic( x );
>      r:= PrimitiveRootMod( p );
>      return LogMod( x![1], r, p ) < LogMod( y![1], r, p );
>    fi;
>    end );
gap> 
gap> InstallMethod( \<,
>    "for element in Z/pZ (ModulusRep) and internal FFE",
>    IsIdenticalObj,
>    [ IsMyZmodpZObj and IsMyModulusRep, IsFFE and IsInternalRep ],
>    function( x, y )
>    return x![1] * One( y ) < y;
>    end );
gap> 
gap> InstallMethod( \<,
>    "for internal FFE and element in Z/pZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsFFE and IsInternalRep, IsMyZmodpZObj and IsMyModulusRep ],
>    function( x, y )
>    return x < y![1] * One( x );
>    end );
]]></Log>
<P/>
Now we install the same methods for the arithmetic operations
<Ref Oper="\+"/>, <Ref Oper="ZeroOp"/>,
<Ref Oper="AdditiveInverseOp"/>,
<C>\-</C>, <Ref Oper="\*"/>,
and <Ref Oper="OneOp"/>
as in the previous section, without listing them below.
Also the same <Ref Attr="Int"/> method is installed
for objects in <C>IsMyZmodnZObj</C>.
Note that it is compatible with the definition of
<Ref Attr="Int"/> for finite
field elements.
And of course the same method for <Ref Oper="\mod"/> is
installed.
<P/>
We have to be careful, however, with the methods for
<Ref Oper="InverseOp"/>,
<Ref Oper="\/"/>, and <Ref Oper="\^"/>.
These methods and the missing methods for arithmetic operations with
one argument in <C>IsMyModulusRep</C> and the other in
<Ref Filt="IsInternalRep"/>
are given below.
<P/>
<Log><![CDATA[
gap> InstallMethod( \+,
>    "for element in Z/pZ (ModulusRep) and internal FFE",
>    IsIdenticalObj,
>    [ IsMyZmodpZObj and IsMyModulusRep, IsFFE and IsInternalRep ],
>    function( x, y ) return x![1] + y; end );
gap> 
gap> InstallMethod( \+,
>    "for internal FFE and element in Z/pZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsFFE and IsInternalRep, IsMyZmodpZObj and IsMyModulusRep ],
>    function( x, y ) return x + y![1]; end );
gap> 
gap> InstallMethod( \*,
>    "for element in Z/pZ (ModulusRep) and internal FFE",
>    IsIdenticalObj,
>    [ IsMyZmodpZObj and IsMyModulusRep, IsFFE and IsInternalRep ],
>    function( x, y ) return x![1] * y; end );
gap> 
gap> InstallMethod( \*,
>    "for internal FFE and element in Z/pZ (ModulusRep)",
>    IsIdenticalObj,
>    [ IsFFE and IsInternalRep, IsMyZmodpZObj and IsMyModulusRep ],
>    function( x, y ) return x * y![1]; end );
gap> 
gap> InstallMethod( InverseOp,
>    "for element in Z/nZ (ModulusRep, nonprime)",
>    [ IsMyZmodnZObjNonprime and IsMyModulusRep ],
>    function( x )
>    local residue;
>    residue:= QuotientMod( 1, x![1], FamilyObj(x)!.modulus );
>    if residue <> fail then
>      residue:= MyZmodnZObj( FamilyObj(x), residue );
>    fi;
>    return residue;
>    end );
gap> 
gap> InstallMethod( InverseOp,
>    "for element in Z/pZ (ModulusRep)",
>    [ IsMyZmodpZObj and IsMyModulusRep ],
>    function( x )
>    local residue;
>    residue:= QuotientMod( 1, x![1], Characteristic( FamilyObj(x) ) );
>    if residue <> fail then
>      residue:= MyZmodnZObj( FamilyObj(x), residue );
>    fi;
>    return residue;
>    end );
]]></Log>
<P/>
The operation <Ref Attr="DegreeFFE" Label="for a FFE"/> is defined
for finite field elements,
we need a method for objects in <C>IsMyZmodpZObj</C>.
Note that we need not require <C>IsMyModulusRep</C> since no access to
representation dependent data occurs.
<P/>
<Log><![CDATA[
gap> InstallMethod( DegreeFFE,
>    "for element in Z/pZ",
>    [ IsMyZmodpZObj ],
>    z -> 1 );
]]></Log>
<P/>
The methods for <Ref Attr="Enumerator"/>,
<Ref Oper="Random" Label="for a list or collection"/>,
<Ref Attr="Size"/>,
and <Ref Attr="Units"/>,
that we had installed in the previous section had all assumed that
their argument contains the whole family of its elements.
So these methods make sense only for the nonprime case.
For the prime case, there are already methods for these operations
with argument a field.
<P/>
<Log><![CDATA[
gap> InstallMethod( Enumerator,
>    "for full ring Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObjNonprime ) and IsWholeFamily ],
>    function( R )
>    local F;
>    F:= ElementsFamily( FamilyObj( R ) );
>    return List( [ 0 .. Size( R ) - 1 ], x -> MyZmodnZObj( F, x ) );
>    end );
gap> 
gap> InstallMethod( Random,
>    "for full ring Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObjNonprime ) and IsWholeFamily ],
>    R -> MyZmodnZObj( ElementsFamily( FamilyObj( R ) ),
>                    Random( 0, Size( R ) - 1 ) ) );
gap> 
gap> InstallMethod( Size,
>    "for full ring Z/nZ",
>    [ CategoryCollections( IsMyZmodnZObjNonprime ) and IsWholeFamily ],
>    R -> ElementsFamily( FamilyObj( R ) )!.modulus );
gap> 
gap> InstallMethod( Units,
>    "for full ring Z/nZ",
>    [     CategoryCollections( IsMyZmodnZObjNonprime )
>      and IsWholeFamily and IsRing ],
>    function( R )
>    local G, gens;
> 
>    gens:= GeneratorsPrimeResidues( Size( R ) ).generators;
>    if not IsEmpty( gens ) and gens[ 1 ] = 1 then
>      gens:= gens{ [ 2 .. Length( gens ) ] };
>    fi;
>    gens:= Flat( gens ) * One( R );
>    return GroupByGenerators( gens, One( R ) );
>    end );
gap> 
gap> InstallTrueMethod( IsFinite,
>    CategoryCollections( IsMyZmodnZObjNonprime ) and IsDomain );
]]></Log>

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Further Improvements in Implementing Residue Class Rings">
<Heading>Further Improvements in Implementing Residue Class Rings</Heading>

There are of course many possibilities to improve the implementation.
<P/>
With the setup as described above,
subsequent calls <C>MyZmodnZ( <A>n</A> )</C> with the same <A>n</A> yield incompatible
rings in the sense that elements of one ring cannot be added to elements
of an other one.
The solution for this problem is to keep a global list of all results of
<C>MyZmodnZ</C> in the current &GAP; session, and to return the stored values
whenever possible.
Note that this approach would admit <Ref Oper="PrintObj"/>
methods that produce &GAP; readable output.
<P/>
One can improve the <Ref Attr="Units"/> method for the full
ring in such a way
that a group is returned and not only a list of its elements;
then the result of <Ref Attr="Units"/> can be used,
e.&nbsp;g., as input for the operation
<Ref Oper="SylowSubgroup"/>.
<P/>
To make computations more efficient,
one can install methods for <C>\-</C>,
<Ref Oper="\/"/>, and <Ref Oper="\^"/>;
one reason for doing so may be that this avoids the unnecessary construction
of the additive or multiplicative inverse, or of intermediate powers.
<P/>
<Log><![CDATA[
InstallMethod( \-, "two elements in Z/nZ (ModulusRep)", ... );
InstallMethod( \-, "Z/nZ-obj. (ModulusRep) and integer", ... );
InstallMethod( \-, "integer and Z/nZ-obj. (ModulusRep)", ... );
InstallMethod( \-, "Z/pZ-obj. (ModulusRep) and internal FFE", ... );
InstallMethod( \-, "internal FFE and Z/pZ-obj. (ModulusRep)", ... );
InstallMethod( \*, "Z/nZ-obj. (ModulusRep) and integer", ... );
InstallMethod( \*, "integer and Z/nZ-obj. (ModulusRep)", ... );
InstallMethod( \/, "two Z/nZ-objs. (ModulusRep, nonprime)", ... );
InstallMethod( \/, "two Z/pZ-objs. (ModulusRep)", ... );
InstallMethod( \/, "Z/nZ-obj. (ModulusRep) and integer", ... );
InstallMethod( \/, "integer and Z/nZ-obj. (ModulusRep)", ... );
InstallMethod( \/, "Z/pZ-obj. (ModulusRep) and internal FFE", ... );
InstallMethod( \/, "internal FFE and Z/pZ-obj. (ModulusRep)", ... );
InstallMethod( \^, "Z/nZ-obj. (ModulusRep, nonprime) & int.", ... );
InstallMethod( \^, "Z/pZ-obj. (ModulusRep), and integer", ... );
]]></Log>
<P/>
The call to <Ref Func="NewType"/> in <C>MyZmodnZObj</C> can be avoided
by storing the required type, e.g., in the family.
But note that it is <E>not</E> admissible to take the type of an existing
object as first argument of <Ref Func="Objectify"/>.
For example, suppose two objects in <C>IsMyZmodnZObj</C> shall be added.
Then we must not use the type of one of the arguments in a call of
<Ref Func="Objectify"/>, because the argument may have knowledge that is not
correct for the result of the addition.
One may think of the property <Ref Prop="IsOne"/>
that may hold for both arguments but certainly not for their sum.
<P/>
For comparing two objects in <C>IsMyZmodpZObj</C> via <Q><C>&lt;</C></Q>,
we had to install a quite expensive method because of the compatibility
with the comparison of finite field elements that did already exist.
In fact &GAP; supports finite fields with elements represented via
discrete logarithms only up to a given size.
So in principle we have the freedom to define a cheaper comparison
via <Q><C>&lt;</C></Q> for objects in <C>IsMyZmodpZObj</C>
if the modulus is large enough.
This is possible by introducing two categories <C>IsMyZmodpZObjSmall</C>
and <C>IsMyZmodpZObjLarge</C>, which are subcategories of <C>IsMyZmodpZObj</C>,
and to install different <Ref Oper="\&lt;"/> methods
for pairs of objects
in these categories.

</Section>
</Chapter>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- %% -->
<!-- %E -->

