Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: Google Sitemap  >>Next: my enum Example17 <<:Perl(6) Today>>

my subtype Examples16 of Perl6 where /^kissu$/

Category: Perl6   Keywords: subtype perl6

应该说类与类型是不一样的,类的英文为 class, 而类型的英文为 type.
虽然在 Perl6 中类和角色(role)通常表现得与类并无不同。可以说 Perl6 中的类型/Type 由类/class, 角色/role, 和子类型/subtype 组成。
通常我们通过子类(subclass)来继承类并添加一些新的属性或方法(增加能力),而我们将通过子类型来限制一些特性(可理解为去掉能力)。

最简单的比如我们要一个只能是偶数的子类型。我们就可以这么定义:

subtype EvenNum of Num where { $^n % 2 == 0 }
首先它继承了类型 Num 然后通过 where 来限定它为偶数($^n 为前面讲过的占位符参数)。
my EvenNum $n;
$n = 2;             # Okay
$n = -2;            # Okay
$n = 0;             # Okay
$n = 3;             # 出错
另一个例子:
subtype Str_not2b of Str where /^[isnt|arent|amnot|aint]$/;
                                                                            
my Str_not2b $hamlet;
$hamlet = 'isnt';   # Okay because 'isnt' ~~ /^[isnt|arent|amnot|aint]$/
$hamlet = 'amnt';   # Bzzzzzzzt!   'amnt' !~ /^[isnt|arent|amnot|aint]$/

detailed

<<Previous: Google Sitemap  >>Next: my enum Example17 <<:Perl(6) Today>>

Options: +Del.icio.us

Related items Created on 2005-06-04 23:59:29, Last modified on 2005-06-05 00:02:56
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.