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

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

Thread Previous
From:
yary
Date:
August 9, 2020 17:53
Subject:
Re: Avoiding monkey typing for custom roles on built-in types...
Message ID:
CAG2CFAa758fj6F7Pobvv1KeM-g+UKVj-P6ZzWWw9Hu=k0YQgfg@mail.gmail.com
I only superficially read this question–but it does make me think of
coercing input types

https://docs.raku.org/language/functions.html#Coercion_types
https://stackoverflow.com/questions/34874779/what-is-the-point-of-coercions-like-intcool

If the methods that do the adding-of-magmas were written with coercion,
would you still want to monkey-type the built-ins?

method add(AddMagma(Cool):D, AddMagma(Cool):D) of AddMagma:D {...}

-y


On Sat, Aug 8, 2020 at 8:05 PM Stuart Hungerford <
stuart.hungerford@gmail.com> wrote:

> 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 Previous


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