Quick Tip #8: Perl 6 sets

作者: 焉知非鱼 | 来源:发表于2016-11-26 21:21 被阅读7次

    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
    

    相关文章

      网友评论

        本文标题:Quick Tip #8: Perl 6 sets

        本文链接:https://www.haomeiwen.com/subject/iiygpttx.html