Quick Tip #8: Perl 6 sets
Set – a collection of unique thingys
Bag - a collection of unique thingys,but weighted for the count of the number of times something is put the bag
Mix - a bag that allows fractional weights
這些是不可變類型。一旦生成就不可變了。每一個都有一個 Hash 版本以允許你更改成員, 但是我會忽略這些。
$ perl6
> my $set = set( 1, 2, 3, 4 )
set(4, 3, 1, 2)
> 4 ∈ $set # member of
True
> 5 ∈ $set # member of
False
> 5 ? $set # not member of
True
> set( 2, 3 ) ? $set # subset of
True
> set( 2, 6 ) ? $set # subset of
False
集合是一種更自然的查看一個值是否存在于一個值的列表中的方式。你可能每一個哈希和使用 :exists
來檢查鍵,但集合會這樣做(盡管那就是 Perl 6 集合現在在幕后為你所做的):
my $set = set( <a b c d> );
my $item = 'h';
say "$item is in set" if $item ∈ $set;
Perl 6擁有將兩個列表轉換為集合的操作符:
$ perl6
> ( 1, 2, 3 ) ∪ ( 4, 5 ) # 并集
set(5, 4, 3, 1, 2)
> ( 1, 2, 4 ) ∩ ( 1, 2, 3 ) # 交集
set(1, 2)
> ( 1, 2, 4 ) ? ( 1, 2, 3 ) # 差集
set(4)
> ( 1, 2, 4 ) ? ( 1, 2, 3 ) # 對稱差分
set(4, 3)
到目前為止,我使用了你在集合數學中看到的奇怪的 Unicode 字符,但每個都有德克薩斯(ASCII)版本:
Texas Fancy Codepoint (hex) Operation
(elem) ∈ U+2208 member of, $a ∈ $set or $a (elem) $set
!(elem) ? U+2209 not a member of, $a ? $set or $a !(elem) $set
(cont) ? U+220B contains,
!(cont) ? U+220C does not contain
(<=) ? U+2286 subset of or equal to,
!(<=) ? U+2288 not subset of nor equal to,
(<) ? U+2282 subset of
!(<) ? U+2284 not subset of
(>=) ? U+2287 superset of or equal to,
!(>=) ? U+2289 not superset of nor equal to,
(>) ? U+2283 superset of
!(>) ? U+2285 not superset of
(<+) ? U+227C baggy subset
!(>+) ? U+227D not baggy subset
有從兩個列表中返回集合的操作符:
Texas Fancy Codepoint (hex) Operation
(|) ∪ U+222A union
(&) ∩ U+2229 intersection
(-) ? U+2216 difference
(^) ? U+2296 symmetric difference
(.) ? U+228D baggy multiplication
(+) ? U+228E baggy addition