method Bridge

Documentation for method Bridge assembled from the following types:

role Real

From Real

(Real) method Bridge

Defined as:

method Bridge(Real:D:)

Default implementation coerces the invocant to Num and that's the behavior of this method in core Real types. This method primarily exist to make it easy to implement custom Real types by users, with the Bridge method returning one of the core Real types (NOT necessarily a Num) that best represent the custom Real type. In turn, this lets all the core operators and methods obtain a usable value they can work with.

As an example, we can implement a custom Temperature type. It has a unit of measure and the value, which are given during instantiation. We can implement custom operators or conversion methods that work with this type. When it comes to regular mathematical operators, however, we can simply use the .Bridge method to convert the Temperature to Kelvin expressed in one of the core numeric types:

class Temperature is Real {
    has Str:D  $.unit  is required where any <K F C>;
    has Real:D $.value is required;
    method new ($value:$unit = 'K'{ self.bless :$value :$unit }
    # Note: implementing .new() that handles $value of type Temperature is left as an exercise 
 
    method Bridge {
        when $!unit eq 'F' { ($!value + 459.67) × 5/9 }
        when $!unit eq 'C' {  $!value + 273.15 }
        $!value
    }
    method gist { self.Str }
    method Str  { "$!value degrees $!unit" }
}
 
sub postfix:<> { Temperature.new: $^value:unit<C> }
sub postfix:<> { Temperature.new: $^value:unit<F> }
sub postfix:<K> { Temperature.new: $^value:unit<K> }
 
my $human := 36.6℃;
my $book  := 451℉;
my $sun   := 5778K;
say $human;                # OUTPUT: «36.6 degrees C␤» 
say $human + $book + $sun# OUTPUT: «6593.677777777778␤» 
say 123+ 456K;           # OUTPUT: «579␤»

As we can see from the last two lines of the output, the type of the bridged result is not forced to be any particular core type. It is a Rat, when we instantiated Temperature with a Rat or when conversion was involved, and it is an Int when we instantiated Temperature with an Int.