arrays - 在 Perl6 中制作部分数组

标签 arrays raku

有没有一种很好的方法来获取从另一个数组派生的部分数组?

示例:给定一个包含 x 个元素的数组,以及一个 Int $index在该数组的元素范围内,我想从 $index + 1 运行一个函数到元素数 - 1。

基本上我想比较数组中的所有元素。比较是元素本身的函数。 (注意我知道函数 eqv ,虽然这不适合这种特殊情况)

我在想诸如此类的事情:

for $!my-array.kv -> $index, $element
{
    for $!my-array[$index+1 .. .elems-1] -> $another-element
    {
        $element.compare($another-element)
    }
}

最佳答案

.elems - 1$_ 上调用方法,这可能是错误的。
如果你打算这样写 $!my-array.elems - 1 ,或者你可以给它一个 lambda *.elems - 1 .通常的 lambda 是 * - 1 (一个 Array 将元素数量化)。
在这种情况下,我将只使用无论如何 * .

$!my-array[$index + 1 .. *]

获取for返回结果,前缀 do .

my @result = do for $!my-array.kv -> $index, $element
{

    do for $!my-array[$index + 1 .. *] -> $another-element
    {
        $element.compare($another-element)
    }
}

使用 map 可能更清楚

$!my-array.kv.map: -> $index, $element {

  $!my-array[$index + 1 .. *].map: -> $another-element {

    $element.compare($another-element)
  }
}

既然你提到了 eqv不合适,这让我相信 .compare返回 True当它们相等时,和 False除此以外。
那么eqv 其实很合适 .你只需要先调整它。

class Foo {
    method compare (Foo:D: Foo:D $other ) {…}
    …
}

# this gets mixed into the existing &infix:«eqv»
# mark it for export so that it is available in other code units
multi sub infix:«eqv» ( Foo:D \left, Foo:D \right ) is export {

  left.compare(right)

}

# must import it everywhere you want the special cased &infix:«eqv»
# as operators are lexically scoped
use Foo;

$!my-array.kv.map: -> $index, $element {
    # cross using &infix:«eqv»
    $element X[eqv] $!my-array[$index + 1 .. *]
}

您也可以使用 «eqv« ( <<eqv<< )。

您所写的内容恰好与 combinations 相吻合.

my @result = $!my-array.combinations(2).map(
  -> ( $a, $b ) { $a eqv $b }
)

这将生成一个平面列表。

< a b c d e >.combinations(2).map: -> ($element, $another-element){
    $element cmp $another-element
}
# (Less,Less,Less,Less,Less,Less,Less,Less,Less,Less)

而前面的代码生成一个列表列表。 (有一个额外的空的)

my @a = < a b c d e >;
say @a.kv.map: -> $index, $value {
  @a[$index ^.. *].map: $value cmp *
}
# (
#   (Less,Less,Less,Less),
#   (Less,Less,Less),
#   (Less,Less),
#   (Less,),
#   (),
# )

请注意,您可以拼写中缀运算符的名称 eqv在几个方面

&infix:«  eqv  »
&infix:<  eqv  >
&infix:[ 'eqv' ]
&[eqv]

在声明一个新的 multi sub 时,除了最后一个都可以使用。执行。
(删除 & 后)

附言我认为一个名为 .compare 的方法应该返回 Order ( LessSameMore )。
那么要调整的正确运算符是 &infix:«cmp» .

关于arrays - 在 Perl6 中制作部分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022468/

相关文章:

raku - 为什么我在调用 HTTP::Request.new 时得到 “Too many positionals passed…”?

raku - Perl 6 中的 urlopen 方法?

java - 链接列表中的多维数组不起作用?

javascript - 计算对象数组上的所有值 - javascript

raku - 递归生成器 - 手动 zip 与运算符

functional-programming - Perl 6使用reduce一次计算int数组的平均值

sequence - 对来自序列的供应使用react

java - 如何将 for 循环与字符串数组对应起来?

C:读取文本文件并操作数据

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 异常?我该如何预防?