This example shows simple use of associative arrays. First we create
an array indexed by rationals.
> A := AssociativeArray();
> A[1/2] := 7;
> A[3/8] := "abc";
> A[3] := 3/8;
> A[1/2];
7
> IsDefined(A, 3);
true 3/8
> IsDefined(A, 4);
false
> IsDefined(A, 3/8);
true abc
> Keys(A);
{ 3/8, 1/2, 3 }
> Values(A);
[* 7, abc, 3/8 *]
> for x in Keys(A) do x, A[x]; end for;
1/2 7
3/8 abc
3 3/8
> Remove(~A, 3/8);
> IsDefined(A, 3/8);
false
> Keys(A);
{ 1/2, 3 }
> Values(A);
[* 7, 3/8 *]
> Universe(A);
Rational Field
We repeat that an associative array can be indexed by elements of any
structure. We now index an array by elements of the symmetric group S
3.
> G := Sym(3);
> A := AssociativeArray(G);
> v := 1; for x in G do A[x] := v; v +:= 1; end for;
> A;
Associative Array with index universe GrpPerm: G, Degree 3, Order 2 * 3
> Keys(A);
{
(1, 3, 2),
(2, 3),
(1, 3),
(1, 2, 3),
(1, 2),
Id(G)
}
> A[G!(1,3,2)];
3
The following shows how the parameter
Default can be used when
an associative array A is created.
> A := AssociativeArray(: Default := []);
> x := 3; y := 5;
> Append(~A[x], y);
> assert A[x] eq [y];
> assert Keys(A) eq {x};
> assert Values(A) eq [* [ y ] *];
> IsDefined(A, x);
true [ 5 ]
> IsInKeys(A, x);
true [ 5 ]
> IsDefined(A, 4);
true []
> IsInKeys(A, 4);
false
Here we can append an element to A[x] even when x is not yet in
the keys of A; in such a case, A[x] is initially taken to be []
and so can be appended to without error.
[Next][Prev] [Right] [Left] [Up] [Index] [Root]