Course of Raku / Advanced / More about built-in types
Sets, bags, and mixes
Besides arrays and hashes, Raku offers a few specialised containers
for collections of values. The simplest is the Set — an
unordered collection of distinct values, where each value is
either a member or not, and duplicates are ignored.
You create a set with the set routine. Repeated values
collapse into one:
my $s = set(1, 2, 3, 2, 1);
say $s.elems; # 3Even though five numbers were passed in, the set has only three
elements, because 1 and 2 appeared more than
once.
The main question you ask a set is whether a value belongs to it. The
∈ operator (read as “is an element of”) returns a
Boolean:
say 2 ∈ set(1, 2, 3); # True
say 9 ∈ set(1, 2, 3); # FalseIf you prefer to stay with plain ASCII, the same operator can be
written as (elem):
say 2 (elem) set(1, 2, 3); # TrueThe following topics show how to combine sets, and introduce bags and mixes, which are close relatives of the set.
Topics in this section
Practice
Complete the quiz that covers the contents of this section.
Exercises
This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.