在 Perl 6 中怎么为已存在的类添加方法?

How do you add a method to an existing class in Perl 6?

Perl 6 中怎么为已存在的类添加方法?

Int 类有一个方法叫做 is-prime, 我想为 Int类型添加其它的方法。

class MyInt is Int {
    method is-even () returns Bool:D {
        return False if self % 2;
        return True;
        }
    }

my $n = MyInt.new(138);
say $n.is-even;

通过类的继承也是一种方法, 但是不是我想要的。Swift 中可以通过扩展来实现, Perl 6 中有一个 add_method方法:

method add_method(Metamodel::MethodContainer: $obj, $name, $code)

这会给元类(meta class)添加一个方法, 使用 $name 作为调用的方法名。这只会在类型被组合前使用。

Int.^add_method( 'is-even', method () returns Bool:D {
    return False if self % 2;
    return True;
    } );

say 137.is-even;
say Int.^methods;

如果我调用 Int.^methods时, is-even没有出现。但是上面的代码能被调用并起作用了。


Int.^add_method('fac', method () returns Int:D {
     return 1 if self == 0;
     return 1 if self == 1;
     my $sum = 1; for 1 .. self  {$sum *= $_}; return $sum;
});

1.fac # 1
5.fac # 120

method 后面的圆括号是方法的签名:

Int.^add_method('power', method (Int $num) returns Int:D {
     return self ** $num;
});

2.power(3).say;  # 8
2.power(10).say; # 1024

词法方法


我可以让方法不依附于任何类, 并且能在对象上调用该方法:

my &is-even = method (Int:D :) returns Bool:D { self %% 2 };

这构建了一个 Callable (查看以下 &is-even.WHAT)。 在签名中, 我把它约束为一个定义了的 Int 类型的值(Int:D), 但是没有给它名字。我在类型约束后面添加冒号来说明第一个参数是调用者。现在我能把这个方法应用到任何我想要的对象上:

say 137.&is-even;
say 138.&is-even;
say "foo".&is-even;  # works, although inside is-even blow up
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2009 有用的和有意思的循环 让我们来看一个基本的例子. 这是一个最简单清晰的语法的例子.在这并没有使用括号来包...
    焉知非鱼阅读 3,698评论 0 0
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,929评论 18 399
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,826评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,384评论 19 139
  • self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainS...
    j了个p阅读 2,586评论 0 0