Home > Raku > A Subset of Red

A Subset of Red

SmokeMachine reported on IRC to have found an unusual use of subset.

class Base {}
class SubClass is Base {}

multi sub trait_mod:<of>(\type, Base $base, |c) { dd type; dd c }

subset Better of SubClass where { put "where: $_"; True };

my Better $a = 42;
# OUTPUT: Better
#         \()
#         where: 42

subset creates a new type with a metaclass of Perl6::Metamodel::SubsetHOW and registers a symbol for it. The of trait is a macro-ish sub that is called at compile time, right after the new type was created. We can get hold of both arguments of that trait and do whatever we want with those type-objects. (There are no further argument, hence the \()).

The where-clause is part of the subset and is called every time we assign a value to a container which is type-checked by the type created with subset. And that is cool. We basically get a callback into container assignment but only for types that are subclasses of a user-defined type. We can even create a fancy runtime error, based on the to be assigned value.

subset Universe of Base where { die 'wrong answer' unless $_ == 42; True }
my Universe $b = 43;
# OUTPUT: wrong answer
            in block  at 2021-03-08.raku line 1513

Red is doing all sorts of fancy meta-programming and I can highly recommend to read its source. With this discovery we got another nice tool in box.

Categories: Raku