当我们检查 reduce 函数时:
my $result = reduce &reduction_procedure, @array;
我们总结出以下对内部工作的简单规则:
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)
这些简单的规则对于缩减元操作符[]同样有效。例如:
example.1
---------
say [+] [1,2,3,4]; # result : 10
例如:缩减规则按原样应用:
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
但以下示例不适用:
example.2
----------
say [<] 1,2,3,4; # result : True
例如,第二个示例中我们观察到一种不一致性:
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)
不一致的地方在于,从第2步开始,我们不能将上一步的结果作为后续reduce操作的第一个参数使用,而是需要通过实际值计算一个逻辑中间结果, 最后在最终步骤中使用“逻辑与”来对每个步骤的中间逻辑结果进行操作:
Reduction Result = True && True && True = True (use of logical AND as "meta-reduction" operator)
所谓“元规约”元操作符,可以说是一种“规约规约”的机制!
问题:
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) ?
say [\+] [1,2,3,4];
输出(1 3 6 10)
)。 - uzluisf