散列也是容器
假設(shè)我們想計算某個東西的出現(xiàn)次數(shù), 我們通常的做法是弄一個 "seen-hash" 散列。有時候我們有一組待查詢的鍵, 其中有些鍵可能不在我們所掃描的數(shù)據(jù)中。那是一種特殊情況, 但是 Perl 6 能夠完美地解決, 因為散列也是容器, 因此我們能夠擁有默認值。
my $words = <Hashes are containers too>.lc;
constant alphabet = 'a' .. 'z';
my %seen of Int is default(0);
%seen{$_}++ for $words.comb;
put "$_: %seen{$_}" for alphabet;
輸出結(jié)果:
a: 3
b: 0
c: 1
d: 0
e: 3
f: 0
g: 0
h: 2
i: 1
j: 0
k: 0
l: 0
m: 0
n: 2
o: 3
p: 0
q: 0
r: 2
s: 3
t: 2
u: 0
v: 0
w: 0
x: 0
y: 0
z: 0
$words
中沒有出現(xiàn)的特殊字符由 is default(0)
處理了。
默認值可以被精心設(shè)計。我們來弄一個在數(shù)值上下文中為默認值為 0 但是在字符串上下文中為默認值為 NULL 并且總是被定義的一個散列。
my %seen of Int is default(0 but role :: { method Str() {'NULL'} });
say %seen<not-there>, %seen<not-there>.defined, Int.new(%seen<not-there>);
# OUTPUT
# ?NULLTrue0
?