减少元操作符不一致性

8

当我们检查 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
1个回答

16

这不是矛盾,而是操作符结合律在Raku中的示例。

写成:

[<] 1,2,3,4

与写作相同:

1 < 2 < 3 < 4

在大多数编程语言中,这种方法是行不通的,但是 < 运算符具有链式结合性,因此它会有效地将其视为:

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

哪个是真的。


1
如果您想创建自己的链式操作符,您需要一个接受 slurpy 数组值的版本,并且知道如何处理它。 - Scimon Proctor
你能举一个自定义链式关联运算符的例子吗? - jakar
我正在进一步调查这个问题。我认为内置的链操作有一些特殊的魔力,用户生成的操作没有得到。但是你可以定义一个列表操作并以这种方式处理它们。 - Scimon Proctor
请注意,标准链操作符都按预期工作,只有自定义的操作符不起作用 :( - Scimon Proctor
是的,我注意到了!可能是个bug!让我们看看你提出的问题的结果。 - jakar
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接