Quick Tip #8: Perl 6 sets

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 昨天羅德買了一張重金屬搖滾CD,上面還貼著家長警告的標簽我還從來沒有聽過值得貼上家長警告的CD,因為爸媽向來不允許...
    吹_9975閱讀 536評論 0 0
  • ”望子成龍,望女成鳳“,這是眾多家長的熱切期盼。的確,當下的教育及社會環境,確實使不少家長產生了焦慮及攀比的心態,...
    左拐再左拐閱讀 1,345評論 0 1
  • 農歷正月十五元宵節,又稱為“上元節”或燈節,是繼春節之后的第一個重要節日。在古書中,這一天稱為“上元”,...
    金石可鏤1閱讀 210評論 0 0
  • 平常我們哪兒有機會傾聽別人的煩惱,也沒人會想找我們咨詢,恐怕一輩子都不會有。這是第一次,也是最后一次。 這是幾個普...
    兮鐘BEGULIER閱讀 511評論 0 2
  • 我從來沒有遇到過愛情 或許 就是有人這么酷 天生不會愛吧
    代號廢魚閱讀 167評論 0 0