21.17 Advanced List Manipulations

The following functions are generalizations of List (see List), Set (see Set), Sum (see Sum), and Product (see Product).

  • ListX( arg1, arg2, ...argn, func ) O

    ListX returns a new list constructed from the arguments.

    Each of the arguments arg1, arg2, ... argn must be one of the following.

    a list or collection
    this introduces a new for-loop in the sequence of nested for-loops and if-statements;

    a function returning a list or collection
    this introduces a new for-loop in the sequence of nested for-loops and if-statements, where the loop-range depends on the values of the outer loop-variables;

    a function returning true or false
    this introduces a new if-statement in the sequence of nested for-loops and if-statements;

    The last argument func must be a function, it is applied to the values of the loop-variables and the results are collected.

    Thus ListX( list, func ) is the same as List( list, func ), and ListX( list, func, x -> x ) is the same as Filtered( list, func ).

    As a more elaborate example, assume arg1 is a list or collection, arg2 is a function returning true or false, arg3 is a function returning a list or collection, arg4 is another function returning true or false. Then the call

    <result> := ListX( <arg1>, <arg2>, <arg3>, <arg4>, <func> )
    
    is equivalent to
    <result> := [];
    for v1 in <arg1> do
        if <arg2>( v1 ) then
            for v2 in <arg3>( v1 ) do
                if <arg4>( v1, v2 ) then
                    Add( <result>, <func>( v1, v2 ) );
                fi;
            od;
        fi;
    od;
    
    The following example shows how ListX can be used to compute all pairs and all strictly sorted pairs of elements in a list.
    gap> l:= [ 1, 2, 3, 4 ];;
    gap> pair:= function( x, y ) return [ x, y ]; end;;
    gap> ListX( l, l, pair );
    [ [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 1 ], [ 2, 2 ], [ 2, 3 ], 
      [ 2, 4 ], [ 3, 1 ], [ 3, 2 ], [ 3, 3 ], [ 3, 4 ], [ 4, 1 ], [ 4, 2 ], 
      [ 4, 3 ], [ 4, 4 ] ]
    
    In the following example, < is the comparison operation:
    gap> ListX( l, l, \<, pair );    
    [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ] ]
    

  • SetX( arg1, arg2, ...func ) O

    The only difference between SetX and ListX is that the result list of SetX is strictly sorted.

  • SumX( arg1, arg2, ...func ) O

    SumX returns the sum of the elements in the list obtained by ListX when this is called with the same arguments.

  • ProductX( arg1, arg2, ...func ) O

    ProductX returns the product of the elements in the list obtained by ListX when this is called with the same arguments.

    [Top] [Previous] [Up] [Next] [Index]

    GAP 4 manual
    February 2000