在Raku中表达双重求和序列

Lar*_*een 13 math raku

如何在Perl 6中表达双变量双求和序列?

有关双变量双求和序列的示例,请参见此

图片

它必须按原样表示,即在数学上不将双重求和简化为单一求和。谢谢。

use*_*601 14

X(交叉算子)和[+](还原metaoperator [ ]与添加剂操作者+)使这个非常容易:

为了表示1双求和?³ X θ=θ1 ?? y?=?1 2x + y,您可以执行以下操作:

  [+] do for 1..3 X 1..5 -> ($x, $y) { 2 * $x + $y }
#        for 1..3 X 1..5                             # loop cross values
#                        -> ($x, $y)                 # plug into x/y
#                                    { 2 * $x + $y } # calculate each iteration
#     do                                             # collect loop return vals 
# [+]                                                # sum them all
Run Code Online (Sandbox Code Playgroud)

如果要为此创建一个sub,则可以将其编写为以下2

sub ?? (
    Int $a?, Int $a?,     # to / from for the outer
    Int $b?, Int $b?,     # to / from for the inner
    &f where .arity = 2   # 'where' clause guarantees only two params
) {
  [+] do for $a?..$a? X $b?..$b? -> ($a, $b) { &f(a,b) }
}

say ?? 1,3, 1,5, { 2 * $^x + $^y }
Run Code Online (Sandbox Code Playgroud)

甚至简化事情来

sub ?? (
    Iterable \a,            # outer values
    Iterable \b,            # inner values
    &f where .arity = 2) {  # ensure only two parameters
  [+] do f(|$_) for a X b
}

# All of the following are equivalent
say ?? 1..3, 1..5, -> $x, $y { 2 * $x  + $y  }; # Anonymous block
say ?? 1..3, 1..5,           { 2 * $^x + $^y }; # Alphabetic args
say ?? 1..3, 1..5,             2 *  *  +  *   ; # Overkill, but Whatever ;-) 
Run Code Online (Sandbox Code Playgroud)

请注意,通过键入它,我们可以确保传递范围,但是通过将其键入为,Iterable而不是Range我们可以允许更有趣的求和序列,例如,?? (1..?).grep(*.is-prime)[^99], 1..10, { … }可以让我们使用前100个素数的序列。

实际上,如果我们确实愿意,我们可以过度使用,并允许使用任意深度求和运算符,这可以通过将函数向左移动来简化:

sub ?? (
    &function, 
    **@ranges where                # slurp in the ranges
        .all   ~~ Iterable &&      # make sure they're Iterables 
        .elems == &function.arity  # one per argument in the function
) {
  [+] do function(|$_) for [X] @ranges;
};
Run Code Online (Sandbox Code Playgroud)

就像[+]总结我们f()函数的所有值一样,[X]迭代计算叉,例如,[X] 0..1, 3..4, 5..6先做0..1 X 3..4or (0,3),(0,4),(1,3),(1,4),然后再做(0,3),(0,4),(1,3),(1,4) X 5..6or (0,3,5),(0,4,5),(1,3,5),(1,4,5),(0,3,6),(0,4,6),(1,3,6),(1,4,6)


1.抱歉,我不允许我使用LaTeX,但是您应该明白这一点。2.是的,我知道这是一个下标字母O,而不是零,下标数字通常不是有效的标识符,但是您可以使用Slang :: Subscripts启用它们。