Hi,
I'm creating some Raku roles that model algebraic structures:
role AddMagma {
method add(AddMagma:D, AddMagma:D) of AddMagma:D {...}
}
role AddSemigroup does AddMagma {
multi method add-associativity(AddSemigroup:D \x, AddSemigroup:D \y)
of Bool:D {
self.add(x.add(y)) == (self.add(x)).add(y)
}
}
All the built-in numeric types are (ignoring floating point issues)
additive magmas and additive semigroups. So my first thought was to
monkey type the appropriate classes to do these roles:
use MONKEY-TYPING;
augment class Int does AddMagma {
method add(Int:D \x) of Int:D {
self + x
}
}
augment class Int does AddSemigroup {}
# and similar for other built-in types.
Then I can test the structure properties with built-in numeric values:
say "Int addition is associative: ", 42.add-associativity(43, 44);
BUT: monkey typing like this is frowned upon (with good reason no doubt)
and can't be done on numeric roles like Numeric, which are "sealed".
Would a better approach be to create custom subtypes of the built-in
numeric types that mixin the algebraic roles? Is there an idiomatic way
avoid boilerplate code in creating instances of these custom subtypes?
Any advice much appreciated,
Stu