2017-12-27 406 views
4

我想用Perl 6編寫一些類來測試Perl 6類和方法。構造函數指向perl6中的類

下面是代碼:

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使用函數指針來選擇我使用的構造函數?

+0

嘗試在聲明'$ hum2_const'時刪除&符:'my $ hum2_const = human2。new;'在'$ hum2_const'前加一個&符號,並在定義'$ c'時刪除括號:'my $ c =&$ hum2_const;' –

回答

3

我認爲這是一個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; 

這是否有意義?

+0

yes。這工作。非常感謝! – BhaskarS

3

要獲得對.new的「引用」,您必須使用元對象協議。
.^lookup.^find_method

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

這仍然不是你看上去很什麼,因爲方法需要一個類的對象或實例,作爲他們的第一個參數。

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

所以你可能想要咖啡類作爲該方法的第一個參數。

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 } 

您也可以將其存儲在& sigiled變量,所以你可以使用它,就好像它是一個正常的子程序。

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

my $c = hum1-create;