这是代码.
2 3 class List_filter { 4 has @.my_List = (1..20); 5 6 method filter($l) { return True; } 7 8 # filter method 9 method filter_lt_10($l) { 10 if ($l > 10) { return False; } 11 return True; 12 } 13 14 # filter method 15 method filter_gt_10($l) { 16 if ($l < 10) { return False; } 17 return True; 18 } 19 20 # expecting a List of (1..10) to be the output here 21 method get_filtered_List_lt_10() { 22 return self.get_filtered_List(&{self.filter_lt_10}); 23 } 24 25 # private 26 method get_filtered_List(&filter_method) { 27 my @newList = (); 28 for @.my_List -> $l { 29 if (&filter_method($l)) { push(@newList,$l); } 30 } 31 return @newList; 32 } 33 } 34 35 my $Listobj = List_filter.new(); 36 37 my @outList = $Listobj.get_filtered_List_lt_10(); 38 say @outList;
期待[1..10]成为这里的输出.但得到以下错误.
Too few positionals passed; expected 2 arguments but got 1 in method filter_lt_10 at ./b.pl6 line 9 in method get_filtered_List_lt_10 at ./b.pl6 line 22 in block <unit> at ./b.pl6 line 37
我在这做错了什么?
解决方法 在Perl 6中将方法作为参数传递要么需要使用MOP(元对象协议)方法,要么按名称传递方法(然后在运行时为您执行查找).但是,如果你没有真正对这些方法中的对象做某事,为什么要使用方法呢?它们也可能是潜艇,你可以作为参数传递.
也许这是最好的例子:
class List_filter { has @.my_List = 1..20; # don't need parentheses sub filter($--> True) { } # don't need code,signature is enough # filter sub sub filter_lt_10($l) { not $l > 10 } # filter sub sub filter_gt_10($l) { not $l < 10 } # private method !get_filtered_List(&filter_sub) { @.my_List.grep(&filter_sub); } # expecting a List of (1..10) to be the output here method get_filtered_List_lt_10() { self!get_filtered_List(&filter_lt_10); }}my $Listobj = List_filter.new();my @outList = $Listobj.get_filtered_List_lt_10();say @outList; # [1 2 3 4 5 6 7 8 9 10]
第一个子过滤器只返回一个常量值(在本例中为True),可以在具有空体的签名中更容易地表示.
filter_lt_10和filter_gt_10 subs只需要否定条件,因此使用not.
get_filtered_List方法应该是私有的,所以通过前缀来使它成为私有方法!
在get_filtered_List_lt_10中,您现在需要使用!调用get_filtered_List!而不是..而你通过前缀&传递filter_lt_10子作为参数. (否则它将被视为对没有任何参数的sub的调用,这将失败).
更改get_filtered_List以使用内置的grep方法:这需要一个Callable块,它接受一个参数,并返回一些True,以包含它所处理的列表的值.由于采用单个参数的子是Callable,我们可以直接指定子.
希望这是有道理的.我试图尽可能接近预期的语义.
一些一般的编程说法:我觉得潜艇的命名令人困惑:我觉得它们应该被称为filter_le_10和filter_ge_10,因为这正是他们所做的事情.另外,如果你真的不想要任何特别的过滤,而只是从一组特定的预定义过滤器中过滤,你可能会更好的方法是使用常量或枚举创建一个调度表,并使用它来指示你的哪个过滤器想要而不是用另一种方法来制作和维护这些信息.
希望这可以帮助.
总结以上是内存溢出为你收集整理的perl6 – 如何将类方法作为参数传递给perl 6中的另一个类方法全部内容,希望文章能够帮你解决perl6 – 如何将类方法作为参数传递给perl 6中的另一个类方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)