在以下示例中,我尝试通过将数组 (@a)“转换”为 Capture 来动态创建 Capture。
考虑代码:
sub f (|c){
say '';
say ' List : ' ~ do {c.list.gist if c.list.elems > 0};
say ' Hash : ' ~ do {c.hash.gist if c.hash.elems > 0};
say '';
}
my $c1 = \(1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9);
my @a = 1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9;
my $c2 = \(|@a);
f(|$c1);
f(|@a);
f(|$c2);
结果是:
List : (1 (2 3) 4 5 6 7 8 9)
Hash : Map.new((t1 => test1, t2 => test2))
List : (1 (2 3) 4 5 t1 => test1 6 7 t2 => test2 8 9)
Hash :
List : (1 (2 3) 4 5 t1 => test1 6 7 t2 => test2 8 9)
Hash :
第一次运行(使用 Capture $c1)按原样运行,产生所需的行为。
动态创建 Capture 的第二次和第三次尝试失败(可能是因为在这些情况下子例程 f 的参数不是所需的 Capture)。
我观察到合并到数组@a 中的对被视为列表的成员,而不是我想要的命名参数。
我知道,在传递给子例程 f 之前,必须有,可以说,数组中的对“展平”,但我不知道如何做到这一点!
谁能给我一个提示?
最佳答案
在类(class)List
有方法 Capture
,这正是您想要的:
my $c = \(1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9);
my @a = 1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9;
my $c2 = @a.Capture;
f(|$c);
f(|$c2);
f(|@a);
sub f (|c){
say() ;
say ' List : ', c.List;
say ' Hash : ', c.Hash;
say();
}
您可以修改函数的定义
f
直接使用列表 @a
.my $c = \(1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9);
my @a = 1,(2,3),4,5, :t1('test1'), 6,7, :t2('test2'), 8,9;
f($c);
f(@a);
sub f (Capture(Any) \c){
say() ;
say ' List : ', c.List;
say ' Hash : ', c.Hash;
say();
}
Capture(Any)
正所谓coercion type .它接受 Any
但强制Capture
,即它(反复)调用方法 Capture
为拿到它,为实现它。另外,通过
Capture
您可以使用模式匹配。因此函数的最后定义 f
可以改为:sub f ( (**@list, *%hash) ) {
#or even sub f ( (*@list, :t1($t),*%hash) ) {
say() ;
say ' List : ', @list;
# say ' test1 : ', $t;
say ' Hash : ', %hash;
say();
}
关于dynamic - 如何动态创建捕获 (Raku),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580454/