Types, classes & roles
Subsets
PartialNamed types that narrow another with a where constraint (not yet enforced in Raku++).
A subset is a named type built from an existing one plus a where predicate. It lets you attach a validity rule to a type and reuse it in signatures and declarations.
Declaring and using a subset #
subset Even of Int where * %% 2; my Even $n = 4; say $n;
Output
4Even is any Int for which * %% 2 (divisible by two) holds. Assigning 4 succeeds.
Gap: a subset'swherepredicate is not yet enforced in Raku++ — assigning (or passing) an odd number should be a type-check failure (as in Rakudo) but is currently accepted. The base type (of Int) is checked; only thewherepart is skipped. Note this differs from a direct parameterwhereconstraint, which is enforced.
Notes #
of Typesets the base type;where predicatenarrows it. Either part is optional —subset Positive where * > 0constrains any value.- The
whereblock receives the candidate as$_(here via the*whatever), and the subset matches when it returns true. - Subsets shine in signatures:
sub f(Even $x) { … }rejects bad arguments at the boundary, turning a run-time check into a dispatch-time one.