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

时间:2016-07-22 21:45:29

标签: perl6

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)中的元素数。什么给了?

2 个答案:

答案 0 :(得分:3)

按预期工作。将范围对象展平为具有@numbers[|$range]的列表,或者使用Range对象上的绑定来处理它们。 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.

答案 1 :(得分:3)

绑定到Scalar container的符号会产生一件事

获取所需内容的选项包括:

  • 使用 static func searchPosts(searchText: String, completionBlock: PFQueryArrayResultBlock) -> PFQuery { /* NOTE: We are using a Regex to allow for a case insensitive compare of usernames. Regex can be slow on large datasets. For large amount of data it's better to store lowercased username in a separate column and perform a regular string compare. */ // let query = PFQuery(className: "ideaPosts").whereKey(("mood"), // matchesRegex: searchText, modifiers: "i") let query = PFQuery(className: "ideaPosts").whereKey(("mood").lowercaseString, equalTo: searchText.lowercaseString) query.orderByAscending("createdAt") query.findObjectsInBackgroundWithBlock(completionBlock) return query } 的前缀获取单个内容的复数视图:@; OR
  • 以不同方式声明范围变量,以便直接使用

对于后一种选择,请考虑以下事项:

numbers[@$range]

绑定到标量容器(# Bind the symbol `numbers` to the value 1..10: my \numbers = [0,1,2,3,4,5,6,7,8,9,10]; # Bind the symbol `rangeA` to the value 1..10: my \rangeA := 1..10; # Bind the symbol `rangeB` to the value 1..10: my \rangeB = 1..10; # Bind the symbol `$rangeC` to the value 1..10: my $rangeC := 1..10; # Bind the symbol `$rangeD` to a Scalar container # and then store the value 1..10 in it:` my $rangeD = 1..10; # Bind the symbol `@rangeE` to the value 1..10: my @rangeE := 1..10; # Bind the symbol `@rangeF` to an Array container and then # store 1 thru 10 in the Scalar containers 1 thru 10 inside the Array my @rangeF = 1..10; say numbers[rangeA]; # (1 2 3 4 5 6 7 8 9 10) say numbers[rangeB]; # (1 2 3 4 5 6 7 8 9 10) say numbers[$rangeC]; # (1 2 3 4 5 6 7 8 9 10) say numbers[$rangeD]; # 10 say numbers[@rangeE]; # (1 2 3 4 5 6 7 8 9 10) say numbers[@rangeF]; # (1 2 3 4 5 6 7 8 9 10) )的符号始终产生单个值。在$rangeD下标中,单个值必须是数字。并且作为单个数字处理的范围产生该范围的长度。