How to apply one signature test to multiple positionals
There are a few ways to approach this but what I'd probably do – and a generally useful pattern – is to use a subset to create a slightly over-inclusive multi and then redispatch the case you shouldn't have included. For the example you provided, that might look a bit like:
subset RealOrMeasure where Real | Measure;
multi infix:<+> ( RealOrMeasure:D $left, RealOrMeasure:D $right ) {
given $left, $right {
when Real, Real { nextsame }
when Real, Measure { $right.clone.add-const($left) }
when Measure, Real { $left.clone.add-const($right) }
when Measure, Measure { my ($result, $argument) = infix-prep $left, $right;
$result.add($argument)}}
}
(Note: I haven't tested this code with Measure
; let me know if it doesn't work. But the general idea should be workable.)
You can add an Int
- method to your class and use signature coercion.
class Foo {
method Int { 110 };
}
multi t( Int() $x ) { $x + 1 };
multi t( Real $x ) { $x.Int + 11 };
say t( 0 );
say t( 0.1 );
say t( Foo.new );