G.3.11 Folding values in indexed arrays

For the semantics of a “fold iteration” see Conventions of the arrays API. For the semantics of a “multi iteration” see Conventions of the arrays API. For the semantics of a “left iteration” see Conventions of the arrays API. For the semantics of a “right iteration” see Conventions of the arrays API.

For the semantics of the parameter OPERATOR see Conventions of the arrays API. For the semantics of the parameter ARRY see Conventions of the arrays API. For the semantics of the parameter ARRYS see Conventions of the arrays API.

Function: mbfl_array_left_fold ACCUM OPERATOR ARRY
Function: mbfl_array_right_fold ACCUM OPERATOR ARRY

Iterate over ARRY and apply OPERATOR to ACCUM and a value from ARRY. OPERATOR is used in a command line as follows:

OPERATOR ACCUM VALUE

ACCUM might be a data variable in which case OPERATOR might store a result in it.

function operator () {
    mbfl_mandatory_nameref_parameter(ACCUM, 1, accumulator)
    mbfl_mandatory_parameter(VALUE,         2, value from arry)
    ACCUM+=$VALUE
}

mbfl_declare_index_array_varref(ARRY, (a b c d e))
mbfl_declare_varref(LACCUM, '0')
mbfl_declare_varref(RACCUM, '0')

mbfl_array_left_fold  _(LACCUM) operator _(ARRY)
"$LACCUM"  ⇒ 0abcde

mbfl_array_right_fold _(RACCUM) operator _(ARRY)
"$RACCUM"  ⇒ 0edcba
Function: mbfl_multi_array_left_fold ACCUM OPERATOR ARRYS
Function: mbfl_multi_array_right_fold ACCUM OPERATOR ARRYS

Iterate over ARRYS and apply OPERATOR to ACCUM and a tuple of values in homologous slots from ARRY. OPERATOR is used in a command line as follows:

OPERATOR ACCUM VALUES

ACCUM might be a data variable in which case OPERATOR might store a result in it; VALUES is an index array holding ARRYS’s homologous slots’ values.

function operator () {
    mbfl_mandatory_nameref_parameter(ACCUM,  1, accumulator)
    mbfl_mandatory_nameref_parameter(VALUES, 2, values from arrys)
    declare -i I
    declare STR

    for ((I=0; I < mbfl_slots_number(VALUES); ++I))
    do STR+=mbfl_slot_qref(VALUES, $I)
    done
    ACCUM+=" $STR"
}

mbfl_declare_index_array_varref(ARRY1, (a b c d e))
mbfl_declare_index_array_varref(ARRY2, (A B C D E))
mbfl_declare_index_array_varref(ARRY3, (q w e r t))
mbfl_declare_index_array_varref(ARRYS, (_(ARRY1) _(ARRY2) _(ARRY3)))

mbfl_declare_varref(L_ACCUM, '0')
mbfl_declare_varref(R_ACCUM, '0')

mbfl_multi_array_left_fold  _(L_ACCUM) 'operator' _(ARRYS)
mbfl_multi_array_right_fold _(R_ACCUM) 'operator' _(ARRYS)

"$L_ACCUM"      ⇒ '0 aAq bBw cCe dDr eEt'
"$R_ACCUM"      ⇒ '0 eEt dDr cCe bBw aAq'

This document describes version 3.0.0-devel.9 of Marcos Bash Functions Library.