Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Raku mixins work with operator overloading?

I could use some help to work out if overloading math operators can be made to work with mixin via does (or but) in a way that avoids the ambiguity error below... this module:

unit module Physics::Error;

role Error is export {
        has Real $.abs-error;
    
        method negate {
            ...
        }
    }
    
    multi prefix:<-> ( Error:D $right) is export {
        ...
    }

used like by this script...

use Physics::Error;

my $x = 12.5 does Error(0.5);
my $z = -$x;

Ambiguous call to 'prefix:<->(Rat+{Physics::Error::Error})'; these signatures all match: (Rat:D \a) (Physics::Error::Error:D $right)

I want my custom operator to always win unambiguously, then for it to implement the core operation and the Error calcs and then return a (Rat+{Physics::Error::Error}).

Big picture is to do math operations that also perform simple error calculations.

like image 709
p6steve Avatar asked Sep 05 '21 19:09

p6steve


1 Answers

Add an is default trait to your multis:

    multi prefix:<-> ( Error:D $right) is export is default {

That said, note jnthn's comment here:

is default is really a last resort, and even if you can get it to work using the mixin approach, you'll find the result is terribly slow, in no small part because mixins trigger deoptimization (falling out of specialized and JIT-compiled code back to the interpreter).

like image 196
2 revs Avatar answered Oct 17 '22 06:10

2 revs