develooper Front page | perl.perl6.users | Postings from August 2020

Avoiding monkey typing for custom roles on built-in types...

Thread Next
From:
Stuart Hungerford
Date:
August 9, 2020 00:05
Subject:
Avoiding monkey typing for custom roles on built-in types...
Message ID:
CAG+kMrFOTkNVec8DOaohpu3hm+-+dg=Tm2oEF5OcphsPimV3VQ@mail.gmail.com
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

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About