指向 perl6 中 class 的构造函数的指针

pointer to constructor to a class in perl6

我正在尝试用 Perl 6 编写一些 类 只是为了测试 Perl 6 类 和方法。

代码如下:

class human1 {
    method fn1() {
        print "#from human1.fn1\n";
    }
}

class human2 {
    method fn1() {
          print "#from human2.fn1\n";
    }
}

my $a = human1.new();
my $b = human2.new();

$a.fn1();
$b.fn1();

print "now trying more complex stuff\n";

my $hum1_const = &human1.new;
my $hum2_const = &human2.new;

my $c = $hum2_const();
$c.fn1();

本质上,我希望能够使用 human1 构造函数或 human2 构造函数来动态构建 $c 对象。但我收到以下错误:

Error while compiling /usr/bhaskars/code/perl/./a.pl6
Illegally post-declared types:
    human1 used at line 23
    human2 used at line 24

如何创建 $c 使用函数指针来选择我使用的构造函数?

我认为这是一个 LTA 错误的案例。据我了解,您想要实现的是一个 lambda,它会为您创建一个新的 human1human2 对象。你这样做的方式不正确,它导致的错误令人困惑。

my $hum1_const = -> { human1.new };
my $hum2_const = -> { human2.new };

将是执行此操作的正确方法。虽然,我认为这有点令人困惑。由于 human1human2 已经是常量,您可以将它们分配给一个变量,然后只需调用 new 即可:

my $the_human = $condition ?? human1 !! human2;
my $c = $the_human.new;
$c.fn1;

这有意义吗?

要获得对 .new 的“引用”,您必须使用元对象协议。
.^lookup, or .^find_method.

my $hum1-create = human1.^find_method('new');

这仍然不是您要找的东西,因为方法需要 class 对象或实例作为它们的第一个参数。

my $c = $hum1-create( human1 );

所以您可能希望将 class 作为该方法的第一个参数。

my $hum1-create = human1.^find_method('new').assuming(human1);

my $c = $hum1-create();

注意 .assuming 在这种情况下基本上与

做同样的事情
-> |capture { human1.^find_method('new').( human1, |capture ) }

所以你可以这样写:

my $hum1-create = -> |capture { human1.new( |capture ) }

或者如果你永远不会给它一个参数

my $hum1-create = -> { human1.new }

您也可以将它存储在一个 & 带符号的变量中,这样您就可以像使用普通子程序一样使用它。

my &hum1-create = human1.^find_method('new').assuming(human1);

my $c = hum1-create;