dynamic - 如何动态创建捕获 (Raku)

标签 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 之前,必须有,可以说,数组中的对“展平”,但我不知道如何做到这一点!

谁能给我一个提示?

最佳答案

在类(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/

相关文章:

Javascript - 创建动态元素然后在元素单击时执行某些操作

c# - 反射是确定动态对象是否存在属性/方法的最佳方法吗?

c++ - 如何在lambda中捕获函数结果?

compilation - Raku 程序编译和执行的顺序(可能是嵌套编译阶段?)

unicode - 为什么 .ords 与 .chars 不一致?

arrays - 如何使用 >> 处理嵌套数组并返回一个平面数组?

android - 在 Android 上动态添加 TextView 到 ScrollView

css - react 动态 CSS

c++ - 样本量 8 还是 16?

loops - 使用 Stata 检查变量是否存在