减少元运算符不一致

问题描述 投票:0回答:1

当我们检查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

例如1,减少规则按原样应用:

    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

例如2,我们观察到不一致之处:

    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)

不一致的是,从Step.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) ?
operators reduce raku
1个回答
16
投票

这不是不一致,而是运算符关联性在 Raku 中如何工作的示例。

写作:

[<] 1,2,3,4

与写作相同:

1 < 2 < 3 < 4

在大多数语言中这不起作用,但是 < operator has chain associativity so it effectively treats this as :

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

这是真的。

© www.soinside.com 2019 - 2024. All rights reserved.