jak*_*kar 8 dynamic capture raku
在以下示例中,我尝试通过将数组 (@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 之前,必须有,可以说,数组中的对“展平”,但我不知道如何做到这一点!
谁能给我一个提示?
在类中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)就是所谓的强制类型。它接受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();
}  
| 归档时间: | 
 | 
| 查看次数: | 120 次 | 
| 最近记录: |