raku - 如何将类方法作为参数传递给perl 6中类的另一个方法

标签 raku function-object

我有一个像下面这样的脚本。意图是有不同的过滤方法来过滤列表。

这是代码。

  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

我在这里做错了什么?

最佳答案

&{self.method}语法对我来说是新的,所以谢谢你。不幸的是,如果需要参数,它就不起作用。您可以使用 sub正如其他海报提到的,但如果您需要使用方法,您可以通过调用 self.^lookup 获取方法,也就是伊丽莎白提到的元对象协议(protocol)的使用。 ('^' 表示您没有调用属于该类的方法,而是调用包含主类的胆量/实现细节的“影子”类的一部分。)

要获取方法,请使用运行 obj.^lookup(method name) ,并通过传入对象本身(通常是“self”)作为第一个参数,然后是其他参数来调用它。要将对象绑定(bind)到函数以便不需要每次都显式添加,请使用 assuming功能。

class MyClass {
  method log(Str $message) { say now ~ " $message"; }
  method get-logger() { return self.^lookup('log').assuming(self); }
}
my &log = MyClass.get-logger();
log('hello'); # output: Instant:1515047449.201730 hello

关于raku - 如何将类方法作为参数传递给perl 6中类的另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48080366/

相关文章:

raku - 在 bin/中创建包含 Perl 5 实用程序脚本的 Perl 6 模块

c++ - std::function 的模板参数是如何工作的? (执行)

raku - 如何打印对象,输入 nqp

installation - Raku - 程序如何验证模块是否安装在本地

java - 函数对象内部类中的变量/对象会怎样?

c++ - classname() 是否等同于类对象?

c++ - 模板和函数对象 - C++

c++ - 解析对临时函数对象的调用中的歧义

class - 在变量中指定 Perl 6 类

perl - 如何控制 Perl 6 中循环的嵌套性?