gpt4 book ai didi

raku - 分配给列表容器混淆

转载 作者:行者123 更新时间:2023-12-03 15:08:54 27 4
gpt4 key购买 nike

我可能患有大脑衰退,但根据有关项目和列表分配的文档( https://docs.raku.org/language/variables#Item_and_list_assignment ),
分配给列表容器(列表上下文)总是触发列表分配。
然而,这似乎与我从代码中得到的内容相冲突(这里在 raku repl 中复制)。

> my %syns-by-name = %(Bq => ["Bq", "becquerel", "becquerels"], C => ["C", "coulomb", "coulombs"],)
{Bq => [Bq becquerel becquerels], C => [C coulomb coulombs]}
> my Str @res = %syns-by-name{'Bq'};
Type check failed in assignment to @res; expected Str but got Array (["Bq", "becquerel", ...) in block <unit> at <unknown file> line 1
> my Str @res = [|%syns-by-name{'Bq'}];
[Bq becquerel becquerels]
这是一个错误,还是我误解了意图是什么......?
Welcome to 𝐑𝐚𝐤𝐮𝐝𝐨™ v2020.10.
Implementing the 𝐑𝐚𝐤𝐮™ programming language v6.d.
Built on MoarVM version 2020.10.

最佳答案

TL;博士 如果非本地项通过赋值可变,则为 Scalar .列表分配不会变平 Scalar项目。 [1]
一个暗示
考虑这个代码:

my %map = :a;
%map<a> = 42;
say %map<a>; # 42
该作业有效,因为:
say %map<a>.VAR.WHAT; # (Scalar)
“列表分配”
考虑这个代码:
my $scalar = 1,2;       # Useless use of constant integer 2
say $scalar; # 1

my @list1 = 1,2; # "list assignment", so RHS is iterated
say @list1; # [1 2]
所以这是项目和列表分配之间的一个区别。
my @list3 = [1,2];      # Again, RHS is iterated
say @list3; # [1 2]

my @list2 = (1,2); # Again, RHS is iterated
say @list2; # [1 2]

my @list4 = 1,(2,3); # Again, RHS is iterated. Second element stays as a `List`.
say @list4; # [1 (2 3)]

my @list5 = 1,[2,3]; # Again, RHS is iterated. Second element stays as an `Array`.
say @list5; # [1 [2 3]]
如果 RHS 上只列出了一项,并且它不是 Scalar ,列表分配将其展平。但在所有其他情况下,列表分配不会使项目变平。
my @list6 = $[1,2];     # RHS is a `Scalar`. So it doesn't get flattened.
say @list6; # [[1 2]]
我好糊涂!
Q打高尔夫球的情况:
my Str @res = %( :a[42,99] )<a>;
这会产生同样的错误。
因为:
say .VAR.WHAT given :a[42,99]<a>;       # (Array)
say .VAR.WHAT given (% = :a[42,99])<a>; # (Scalar)
脚注
[1] 当猜测产生惊喜,而您将其转化为学习时,您就意识到并理想化了对 ERN 的投资。 ing。

关于raku - 分配给列表容器混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65456629/

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