Sets, Bags and Mixes

Elements with integer counts Elements with real-number weights

my $fruits = set <apple banana cherry>;
my $citrus = set <lemon orange banana>;
say 'apple' ∈ $fruits, ' ', 'apple' (elem) $citrus;   # True False
say $fruits ∪ $citrus;                    # union
say $fruits ∩ $citrus;                    # intersection: Set(banana)
say $fruits ∖ $citrus;                    # difference (also (-))
say $fruits ⊖ $citrus;                    # symmetric difference
say set(<apple>) ⊆ $fruits;               # True (subset)
say $fruits.elems, ' ', $fruits.keys.sort;

my $words = bag <the cat the dog the end>;
say $words<the>, ' ', $words<missing>;    # 3 0
say $words.total, ' ', $words.kxxv.elems; # 6 6
say $words.sort(-*.value).head(2);        # most common
my $mix = mix 'a' => 0.5, 'b' => 1.5;
say $mix.total;                            # 2
say $mix.roll(5);                          # weighted random picks

my %seen is SetHash;
%seen.set('x'); %seen{'y'} = True;
say %seen.keys.sort;                       # (x y)
my %inventory is BagHash = <apple apple pear>;
%inventory<apple>--;
say %inventory;                            # BagHash(apple pear)
say (1, 2, 2, 3).Bag.grep(*.value > 1)».key;   # duplicates: (2)