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

标签 raku

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/

相关文章:

regex - 在字符类中包含不间断的空格

https - 如何配置 Bailador 通过 TLS (HTTPS) 提供内容?

raku - 为什么 `will end` 在程序级范围内的行为与 `will leave` 不同?

raku - 出于调试目的,如何在运行时重新加载 raku 模块?

regex - Perl 6 语法与我认为的不匹配

roles - 对象、角色和多重分派(dispatch)

Raku 中的类似 Haskell 的模式匹配

使用元运算符进行测试不会打印测试描述

unicode - 使用十六进制名称组合字符

set - Perl 6 中的元素成员资格如何工作?