list[ pos ]
The above construct evaluates to the pos-th element of the list list. pos must be a positive integer. List indexing is done with origin 1, i.e., the first element of the list is the element at position 1.
gap> l := [ 2, 3, 5, 7, 11, 13 ];; gap> l[1]; 2 gap> l[2]; 3 gap> l[6]; 13
If list does not evaluate to a list, or pos does not evaluate to a
positive integer, or list[pos]
is unbound an error is signalled.
As usual you can leave the break loop (see Break Loops) with quit;
.
On the other hand you can return a result to be used in place of the list
element by return expr;
.
list{ poss }
The above construct evaluates to a new list new whose first element is
list[poss[1]]
, whose second element is list[poss[2]]
, and so
on. poss must be a dense list of positive integers, it need, however,
not be sorted and may contain duplicate elements. If for any i,
list[ poss[i] ]
is unbound, an error is signalled.
gap> l := [ 2, 3, 5, 7, 11, 13, 17, 19 ];; gap> l{[4..6]}; [ 7, 11, 13 ] gap> l{[1,7,1,8]}; [ 2, 17, 2, 19 ]
The result is a new list, that is not identical to any other list. The elements of that list however are identical to the corresponding elements of the left operand (see Identical Lists).
It is possible to nest such sublist extractions, as can be seen in the following example.
gap> m := [ [1,2,3], [4,5,6], [7,8,9], [10,11,12] ];; gap> m{[1,2,3]}{[3,2]}; [ [ 3, 2 ], [ 6, 5 ], [ 9, 8 ] ] gap> l := m{[1,2,3]};; l{[3,2]}; [ [ 7, 8, 9 ], [ 4, 5, 6 ] ]
Note the difference between the two examples. The latter extracts elements 1, 2, and 3 from m and then extracts the elements 3 and 2 from this list. The former extracts elements 1, 2, and 3 from m and then extracts the elements 3 and 2 from each of those element lists.
To be precise. With each selector [pos]
or {poss}
we associate
a level that is defined as the number of selectors of the form
{poss}
to its left in the same expression. For example
l[pos1]{poss2}{poss3}[pos4]{poss5}[pos6] level 0 0 1 1 1 2
Then a selector list[pos]
of level level is computed as
ListElement(list,pos,level)
, where ListElement
is defined as
follows
ListElement := function ( list, pos, level ) if level = 0 then return list[pos]; else return List( list, elm -> ListElement(elm,pos,level-1) ); fi; end;
and a selector list{poss}
of level level is computed as
ListElements(list,poss,level)
, where ListElements
is defined as
follows
ListElements := function ( list, poss, level ) if level = 0 then return list{poss}; else return List( list, elm -> ListElements(elm,poss,level-1) ); fi; end;
GAP 3.4.4