我想在映射例程中使用数组的索引。例如,这个 Raku 代码:
raku -e 'my @a = "First", "Second", "Third", "First"; say @a.map({ "Index of $_ is: ;" })'
打印:
(Index of First is: ; Index of Second is: ; Index of Third is: ; Index of First is: ;)
是否可以获取数组的索引,例如:
(Index of First is: 0; Index of Second is: 1; Index of Third is: 2; Index of First is: 3;)
谢谢!
.kv
来生成“键”和值。对于数组,键是索引 0、1、2...
>>> my @a = "First", "Second", "Third", "First";
[First Second Third First]
>>> @a.kv
(0 First 1 Second 2 Third 3 First)
这是一个长度为2N的平坦序列;我们可以通过显式签名告诉
map
一次获取 2 件事:
>>> @a.kv.map(-> $index, $value { "Index of $value is $index;" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
或通过占位符变量:
>>> @a.kv.map({ "Index of $^value is $^index;" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
由于 index 按字典顺序出现在 value 之前,因此其工作方式与之前的显式签名情况相同,即在幕后为我们生成相同的签名。我们可以看到这个:
>>> &{ $^value, $^index }
-> $index, $value { #`(Block|140736965530488) ... }
请注意,重要的是变量名称的 Unicode 顺序,而不是出现的顺序。
本着 TIMTOWDI 的精神,一些替代方案(IMO 不是更好):
# Limitation: generated anew per closure and per mention,
# so cannot use, e.g., in string interpolations with closure and more than once
>>> @a.map({ "Index of $_ is " ~ $++ ~ ";" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
.pairs
(.kv
的表弟)来生成“键=>值”对而不是平面列表>>> @a.pairs
(0 => First 1 => Second 2 => Third 3 => First)
# Reach over .key & .value
>>> @a.pairs.map({ "Index of $_.value() is $_.key();" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
# Unpack with signature
>>> @a.pairs.map(-> (:key($index), :$value) { "Index of $value is $index;" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
# Array.keys produces 0, 1, 2...
>>> @a.keys.map({ "Index of @a[$_] is $_;" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
# ^@a is equivalent to ^@a.elems === 0 ..^ @a.elems, i.e., 0, 1, 2... again
>>> ^@a .map({ "Index of @a[$_] is $_;" })
(Index of First is 0; Index of Second is 1; Index of Third is 2; Index of First is 3;)
我认为最后一个是最不惯用的。