operatorsreduceraku

Reduction meta-operator inconsistency


When we examine the reduce function:

    my $result = reduce &reduction_procedure, @array;

we conclude with the following simple rules to the inner workings:

    Reduction Rules
    ---------------
    1. For the first pair of objects from our input (@array)
       we apply the reduction procedure (&reduction_procedure) and we get our first result.

    2. We apply the reduction procedure (&reduction_procedure) to the result (object)
       of the previous rule and the next input (object) from our input (@array),
       and we get an intermediate result (object).

    3. We run rule.2 for every of the remaining objects from our input (@array)

This simple rules work also the same for the reduction metaoperator []. For example:

    example.1
    ---------
    say [+] [1,2,3,4]; # result : 10

For example.1 the reduction rules apply as is:

    Step.1 use Rule.1 : 1 + 2 = 3     1(first value)     + 2(second value)  = 3
    Step.2 use Rule.2 : 3 + 3 = 6     3(previous result) + 3(current value) = 6
    Step.3 use Rule.2 : 6 + 4 = 10    6(previous result) + 4(current value) = 10

but NOT for the following example:

    example.2
    ----------
    say [<] 1,2,3,4;   # result : True

For example.2 we observe an inconsistency:

    Step.1 use Rule.1 : 1 < 2 = True    1(first value)         <  2(second value)      = True
    Step.2 use Rule.2 : 2 < 3 = True    True(previous result) &&  True(current result) = True
    Step.3 use Rule.2 : 3 < 4 = True    True(previous result) &&  True(current result) = True(result)

The inconsistency is that from Step.2 and onwards we can NOT use the result of the previous step as the first parameter of subsequent reduce operations, but instead we calculate a logical intermediate result, with use of the actual values and finally we add as a final step the use of "logical AND" upon the intermediate logical results of each step:

    Reduction Result = True && True && True = True (use of logical AND as "meta-reduction" operator)

Sort of speak we have a "meta-reduction" metaoperator!

Questions:

    1. Is that an inconsistency with a purpose?

    2. Can we exploit this behavior? For instance instead of use of && (logical AND)
       as "meta-reduction" operator can we use || (logical OR) or ?^ (logical XOR) ?

Solution

  • It is not an inconsistency but and example of how operator associativity works in Raku.

    Writing :

    [<] 1,2,3,4
    

    Is the same as writing :

    1 < 2 < 3 < 4
    

    In most languages this wouldn't work but the < operator has chain associativity so it effectively treats this as :

    (1 < 2) and (2 < 3) and (3 < 4)
    

    Which is True.