Skip to content

Commit 2dda092

Browse files
committed
Elaborate a bit about Set.new and my %s is Set
Noting the new parameterization feature as available since 2019.01
1 parent 7f4fa0c commit 2dda092

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

doc/Type/Set.pod6

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,45 @@ keys mapped to values which boolify to C<False> are skipped:
5050
say $n.keys.map(&WHAT); # OUTPUT: «((Str) (Str))␤»
5151
5252
Furthermore, you can get a C<Set> by using set operators (see next section) on
53-
objects of other types such as L<List|/type/List>, which will internally call C<.Set>
54-
on them before performing the operation. Be aware of the tight precedence of
55-
those operators though, which may require you to use parentheses around arguments:
53+
objects of other types such as L<List|/type/List>, which will act like they
54+
internally call C<.Set> on them before performing the operation. Be aware of
55+
the tight precedence of those operators though, which may require you to use
56+
parentheses around arguments:
5657
5758
say (1..5) (^) 4; # OUTPUT: «set(1, 2, 3, 5)␤»
5859
60+
Of course, you can also create a C<Set> with the C<.new> method.
61+
62+
my $fruits = Set.new( <peach apple orange apple apple> );
63+
64+
Since 6.d (2019.01 and later) you can also use this syntax for parameterization
65+
of the C<Set>, to specify which type of values are acceptable:
66+
67+
# only allow strings (Str) in the Set
68+
my $fruits = Set[Str].new( <peach apple orange apple apple> );
69+
70+
# only allow whole numbers (Int) in the Set
71+
my $fruits = Set[Int].new( <peach apple orange apple apple> );
72+
# Type check failed in binding; expected Int but got Str ("peach")
73+
74+
Finally, you can create Set masquerading as a hash by using the C<is> trait:
75+
76+
my %s is Set = <a b c>;
77+
say %s<a>; # True
78+
say %s<d>; # False
79+
80+
Since 6.d (2019.01 and later), this syntax also allows you to specify the
81+
type of values you would like to allow:
82+
83+
# limit to strings
84+
my %s is Set[Str] = <a b c>;
85+
say %s<a>; # True
86+
say %s<d>; # False
87+
88+
# limit to whole numbers
89+
my %s is Set[Int] = <a b c>;
90+
# Type check failed in binding; expected Int but got Str ("a")
91+
5992
=head1 Operators
6093
6194
Perl 6 provides common set operators, which can take C<Set>s (or any other
@@ -92,4 +125,4 @@ L<Sets, Bags, and Mixes|/language/setbagmix>
92125
93126
=end pod
94127

95-
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
128+
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6

0 commit comments

Comments
 (0)