Quick Tip #19: 創(chuàng)建可重用的數據類型
Perl 6 允許你使用類型來約束變量值,但是你不必拘泥于內置類型维咸。一旦你定義了自己的類型回懦,它們就表現得像內置類型一樣闽撤。
下面是我從布拉德的 Subsets::Common模塊偷得的一些子集(subsets):
my package EXPORT::DEFAULT {
...
subset Pos of Numeric where * > 0;
subset Neg of Numeric where * < 0;
subset Zero of Numeric where * == 0;
subset UNumeric of Numeric where * >= 0;
subset Even of Int where * % 2 == 0;
subset Odd of Int where * % 2;
subset Time::Hour12 of PosInt where * ~~ 1 .. 12;
subset Time::Hour24 of Int where * ~~ 0 .. 23;
subset Time::Minute of Int where * ~~ 0 .. 59;
subset Time::Second of Int where * ~~ 0 .. 59;
...
}
subset
關鍵字開啟子集的聲明, 后面跟著你想要的新類型的名字。這是一個子集届惋,因為你基于已經存在的類型使用 of
關鍵字來聲明該子集。在那之后贩据,你可以使用一個 where
從句來改進你的新類型荣病。
并且码撰,布拉德把這些子集都放在了包里而且聲明所有東西都是可導出的。
我也創(chuàng)建了一個 Perl 6 版本的 Chemistry::Elements个盆。不要太在意代碼中有什么東西, 多考慮你要聲明的值是否滿足你想要的約束脖岛。下面這個例子我聲明了一個類型用來約束一個整數為一個已知的原子數:
subset ZInt of Cool is export where {
state ( $min, $max ) = %names.keys.sort( { $^a <=> $^b } ).[0,*-1];
( $_.truncate == $_ and $min <= $_ <= $max )
or
note "Expected a known atomic number between $min and $max, but got $_"
and
False;
};
對于我這個子集, 我通過把它聲明為 is export
來導出它,以至于其它使用該模塊的人能夠從這個模塊的外部使用這個類型颊亮。特別要注意的是柴梆,當給定的值不匹配時我可以指定一個特殊的錯誤提示信息。
文章下面還評論說:
“where * ~~ 0..59” is redundant; since it’s already being smart-matched, this can just be “where 0..59”.
意思是 where * ~~ 0..59
是多余的编兄,因為它已經被智能匹配,它可以只寫為 where 0..59
声登。