有没有一种很好的方法来获得从另一个数组派生的部分数组?
示例:给定一个具有x个元素的数组,并且Int $index在该Array的元素范围内,我想从一个$index + 1元素的数量运行一个函数- 1.
基本上我想比较数组中的所有元素.比较是元素本身的功能.(注意我知道这个功能eqv,虽然这不适合这种特殊情况)
我在考虑以下内容:
for $!my-array.kv -> $index, $element
{
for $!my-array[$index+1 .. .elems-1] -> $another-element
{
$element.compare($another-element)
}
}
Run Code Online (Sandbox Code Playgroud)
.elems - 1调用方法$_,这可能是错误的.
如果你打算这样写$!my-array.elems - 1,或者你可以给它一个lambda *.elems - 1.通常的lambda是* - 1(一个数组代表元素的数量).
在这种情况下,我只会使用Whatever *.
$!my-array[$index + 1 .. *]
Run Code Online (Sandbox Code Playgroud)
要for返回结果,请在其前面加上do.
my @result = do for $!my-array.kv -> $index, $element
{
do for $!my-array[$index + 1 .. *] -> $another-element
{
$element.compare($another-element)
}
}
Run Code Online (Sandbox Code Playgroud)
使用起来可能更清楚 map
$!my-array.kv.map: -> $index, $element {
$!my-array[$index + 1 .. *].map: -> $another-element {
$element.compare($another-element)
}
}
Run Code Online (Sandbox Code Playgroud)
既然你提到了eqv不合适的东西,那就会让我相信当它们是等价的时候就会.compare返回.
那么实际上是合适的.你只需要先调整它.TrueFalseeqv
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)
}
Run Code Online (Sandbox Code Playgroud)
# 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 .. *]
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用«eqv«(<<eqv<<).
你所写的内容恰好与之密切相关combinations.
my @result = $!my-array.combinations(2).map(
-> ( $a, $b ) { $a eqv $b }
)
Run Code Online (Sandbox Code Playgroud)
这会产生一个平面列表.
< 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)
Run Code Online (Sandbox Code Playgroud)
而前面的代码生成列表列表.(额外空的)
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,),
# (),
# )
Run Code Online (Sandbox Code Playgroud)
请注意,您可以通过eqv多种方式拼写中缀运算符的名称
&infix:« eqv »
&infix:< eqv >
&infix:[ 'eqv' ]
&[eqv]
Run Code Online (Sandbox Code Playgroud)
在声明新multi sub实现时,可以使用除最后一个之外的所有实现.
(删除后&)
PS我觉得一个名为方法.compare应返回Order(Less,Same,More).
那么正确的运算符就是调整&infix:«cmp».
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |