-6ren">
gpt4 book ai didi

list - 为什么我在标量上看到下标的奇怪行为?

转载 作者:行者123 更新时间:2023-12-04 22:19:21 24 4
gpt4 key购买 nike

看起来好像标量本身就是一个项目的列表:

> "foo"[1]
Index out of range. Is: 1, should be in 0..0
in block <unit> at <unknown file> line 5

> "foo"[0]
foo
> "foo"[*-1]
foo

我说的是一个列表,因为列表的索引似乎没有范围:
> (0, 1, 2)[3]
Nil

这里发生了什么。我对 [] 运算符有什么不了解。

最佳答案

这是 Any 的一个特性。来自 the docs :

Since Perl 6 intentionally confuses items and single-element lists, most methods in Any are also present on class List, and coerce to List or a list-like type.



如果您使用 look at the implementation ,您会看到没有实际的强制转换必要,因为 Any 提供 AT-POS ,这对于不同于 0 的索引是失败的。

相比之下, implementation of actual lists 仅在索引为负的情况下失败,否则返回 Nil

从语义上讲,这并不完全是疯狂的,因为将 Nil 视为一种安静的失败的一种方式,但这确实是一种不一致。这可能是设计使然,因为项目的“列表性”只是一个方便的功能,而不是界面的一部分,因此如果被滥用,可能会大声提示。

请注意, Array 通过默认返回 Any 给出了第三种行为,这可以在自动激活的上下文中理解。

关于list - 为什么我在标量上看到下标的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39944659/

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