gpt4 book ai didi

raku - 使用 Range 变量作为下标获取位置切片

转载 作者:行者123 更新时间:2023-12-04 06:22:44 25 4
gpt4 key购买 nike

my @numbers =  <4 8 15 16 23 42>;

这个有效:

.say for @numbers[0..2]
# 4
# 8
# 15

但这不是:

my $range = 0..2;
.say for @numbers[$range];
# 16

下标似乎将 $range 解释为范围 (3) 中的元素数。什么给了?

最佳答案

按预期工作。使用 @numbers[|$range] 将范围对象展平为列表或者在 Range 对象上使用绑定(bind)来传递它们。 https://docs.perl6.org将很快更新。

On Fri Jul 22 15:34:02 2016, gfldex wrote:
> my @numbers = <4 8 15 16 23 42>; my $range = 0..2; .say for
> @numbers[$range];
> # OUTPUT«16␤»
> # expected:
> # OUTPUT«4␤8␤15␤»
>
This is correct, and part of the "Scalar container implies item" rule.
Changing it would break things like the second evaluation here:

> my @x = 1..10; my @y := 1..3; @x[@y]
(2 3 4)
> @x[item @y]
4

Noting that since a range can bind to @y in a signature, then Range being a
special case would make an expression like @x[$(@arr-param)]
unpredictable in its semantics.

> # also binding to $range provides the expected result
> my @numbers = <4 8 15 16 23 42>; my $range := 0..2; .say for
> @numbers[$range];
> # OUTPUT«4␤8␤15␤»
> y

This is also expected, since with binding there is no Scalar container to
enforce treatment as an item.

So, all here is working as designed.

关于raku - 使用 Range 变量作为下标获取位置切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38535690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com