[Pdx-pm] Musings on operator overloading
Jonathan Leto
jaleto at gmail.com
Sun Feb 24 15:14:17 PST 2008
Howdy Folks,
[snip]
> Note that even with mathematical abstractions, there are cases
> where scope-bound overloading is a win over type-bound
> overloading. Consider a hypothetical Math::Symbolic that lets you
> do something like this:
>
> my $x = Math::Symbolic->new();
> print +( $x**2 + 4 * $x + 3 )->derivative( $x );
>
> I hope it?s obvious how such a thing would me implemented. Now,
> if you used type-bound overloading, then the following two
> expressions cannot yield the same result:
>
> ( 2 / 3 ) * $x
> 2 * $x / 3
>
> But if overloading was scope-bound, they would!
[snip]
This piqued my interest, so I attempted to exhibit the problem with
Math::MatrixReal (which uses a fair bit of op overloading) :
#!/usr/bin/perl -w
use strict;
use Math::MatrixReal;
# Example code to show type bound operator overloading
# that returns the same stuff
my $matrix = Math::MatrixReal->new_from_rows([[3,6,9]]);
my $a = (2/3) * $matrix;
my $b = 2 * $matrix / 3;
my $c = 2 * (+$matrix) / 3;
my $d = (2/3) * (+$matrix);
print "\$a is a " . (ref $a) . "\n";
print "\$b is a " . (ref $b) . "\n";
print "\$c is a " . (ref $c) . "\n";
print "\$d is a " . (ref $d) . "\n";
print "\$a=\n";
print $a;
print "\$b=\n";
print $b;
print "\$c=\n";
print $c;
print "\$d=\n";
print $d;
Which outputs:
$a is a Math::MatrixReal
$b is a Math::MatrixReal
$c is a Math::MatrixReal
$d is a Math::MatrixReal
$a=
[ 2.000000000000E+00 4.000000000000E+00 6.000000000000E+00 ]
$b=
[ 2.000000000000E+00 4.000000000000E+00 6.000000000000E+00 ]
$c=
[ 2.000000000000E+00 4.000000000000E+00 6.000000000000E+00 ]
$d=
[ 2.000000000000E+00 4.000000000000E+00 6.000000000000E+00 ]
Am I missing something?
The current source for Math::MatrixReal is at
http://leto.net/svn/Math-MatrixReal/
and the source to that example can be found at
http://leto.net/svn/util/trunk/examples/ .
--
[---------------------]
Jonathan Leto
jaleto at gmail.com
503.928.0609
More information about the Pdx-pm-list
mailing list