ption is set, and not via C command.
If one attempts to print this value, then the overloaded operator
C<""> will be called, which will call C operator. The
result of this operator will be stringified again, but this result is
again of type C, which will lead to an infinite loop.
Add a pretty-printer method to the module F:
sub pretty {
my ($meth, $a, $b) = @{+shift};
$a = 'u' unless defined $a;
$b = 'u' unless defined $b;
$a = $a->pretty if ref $a;
$b = $b->pretty if ref $b;
"[$meth $a $b]";
}
Now one can finish the script by
print "side = ", $side->pretty, "\n";
The method C is doing object-to-string conversion, so it
is natural to overload the operator C<""> using this method. However,
inside such a method it is not necessary to pretty-print the
I $a and $b of an object. In the above subroutine
C<"[$meth $a $b]"> is a catenation of some strings and components $a
and $b. If these components use overloading, the catenation operator
will look for an overloaded operator C<.>; if not present, it will
look for an overloaded operator C<"">. Thus it is enough to use
use overload nomethod => \&wrap, '""' => \&str;
sub str {
my ($meth, $a, $b) = @{+shift};
$a = 'u' unless defined $a;
$b = 'u' unless defined $b;
"[$meth $a $b]";
}
Now one can change the last line of the script to
print "side = $side\n";
which outputs
side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
and one can inspect the value in debugger using all the possible
methods.
Something is still amiss: consider the loop variable $cnt of the
script. It was a number, not an object. We cannot make this value of
type C, since then the loop will not terminate.
Indeed, to terminate the cycle, the $cnt should become false.
However, the operator C for checking falsity is overloaded (this
time via overloaded C<"">), and returns a long string, thus any object
of type C is true. To overcome this, we need a way to
compare an object to 0. In fact, it is easier to write a numeric
conversion routine.
Here is the text of F with such a routine added (and
slightly modified str()):
package symbolic; # Primitive symbolic calculator
use overload
nomethod => \&wrap, '""' => \&str, '0+' => \#
sub new { shift; bless ['n', @_] }
sub wrap {
my ($obj, $other, $inv, $meth) = @_;
($obj, $other) = ($other, $obj) if $inv;
bless [$meth, $obj, $other];
}
sub str {
my ($meth, $a, $b) = @{+shift};
$a = 'u' unless defined $a;
if (defined $b) {
"[$meth $a $b]";
} else {
"[$meth $a]";
}
}
my %subr = ( n => sub {$_[0]},
sqrt => sub {sqrt $_[0]},
'-' => sub {shift() - shift()},
'+' => sub {shift() + shift()},
'/' => sub {shift() / shift()},
'*' => sub {shift() * shift()},
'**' => sub {shift() ** shift()},
);
sub num {
my ($meth, $a, $b) = @{+shift};
my $subr = $subr{$meth}
or die "Do not know how to ($meth) in symbolic";
$a = $a->num if ref $a eq __PACKAGE__;
$b = $b->num if ref $b eq __PACKAGE__;
$subr->($a,$b);
}
All the work of numeric conversion is done in %subr and num(). Of
course, %subr is not complete, it contains only operators used in the
example below. Here is the extra-credit question: why do we need an
explicit recursion in num()? (Answer is at the end of this section.)
Use this module like this:
require symbolic;
my $iter = symbolic->new(2); # 16-gon
my $side = symbolic->new(1);
my $cnt = $iter;
while ($cnt) {
$cnt = $cnt - 1; # Mutator '--' not implemented
$side = (sqrt(1 + $side**2) - 1)/$side;
}
printf "%s=%f\n", $side, $side;
printf "pi=%f\n", $side*(2**($iter+2));
It prints (without so many line breaks)
[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
[n 1]] 2]]] 1]
[/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
pi=3.182598
The above module is very primitive. It does not implement
mutator methods (C<++>, C<-=> and so on), does not do deep copying
(not required without mutators!), and implements only those arithmetic
operations which are used in the example.
To implement most arithmetic operations is easy; one should just use
the tables of operations, and change the code which fills %subr to
my %subr = ( 'n' => sub {$_[0]} );
foreach my $op (split " ", $overload::ops{with_assign}) {
$subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split " ", "@overload::ops{ @bins }") {
$subr{$op} = eval "sub {shift() $op shift()}";
}
foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
print "defining '$op'\n";
$subr{$op} = eval "sub {$op shift()}";
}
Since subroutines implementing assignment operators are not required
to modify their operands (see L above),
we do not need anything special to make C<+=> and friends work,
besides adding these operators to %subr and defining a copy
constructor (needed since Perl has no way to know that the
implementation of C<'+='> does not mutate the argument -
see L).
To implement a copy constructor, add C<< '=' => \&cpy >> to C
line, and code (this code assumes that mutators change things one level
deep only, so recursive copying is not needed):
sub cpy {
my $self = shift;
bless [@$self], ref $self;
}
To make C<++> and C<--> work, we need to implement actual mutators,
either directly, or in C. We continue to do things inside
C, thus add
if ($meth eq '++' or $meth eq '--') {
@$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
return $obj;
}
after the first line of wrap(). This is not a most effective
implementation, one may consider
sub inc { $_[0] = bless ['++', shift, 1]; }
instead.
As a final remark, note that one can fill %subr by
my %subr = ( 'n' => sub {$_[0]} );
foreach my $op (split " ", $overload::ops{with_assign}) {
$subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split " ", "@overload::ops{ @bins }") {
$subr{$op} = eval "sub {shift() $op shift()}";
}
foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
$subr{$op} = eval "sub {$op shift()}";
}
$subr{'++'} = $subr{'+'};
$subr{'--'} = $subr{'-'};
This finishes implementation of a primitive symbolic calculator in
50 lines of Perl code. Since the numeric values of subexpressions
are not cached, the calculator is very slow.
Here is the answer for the exercise: In the case of str(), we need no
explicit recursion since the overloaded C<.>-operator will fall back
to an existing overloaded operator C<"">. Overloaded arithmetic
operators I fall back to numeric conversion if C is
not explicitly requested. Thus without an explicit recursion num()
would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
the argument of num().
If you wonder why defaults for conversion are different for str() and
num(), note how easy it was to write the symbolic calculator. This
simplicity is due to an appropriate choice of defaults. One extra
note: due to the explicit recursion num() is more fragile than sym():
we need to explicitly check for the type of $a and $b. If components
$a and $b happen to be of some related type, this may lead to problems.
=head2 I Symbolic Calculator
One may wonder why we call the above calculator symbolic. The reason
is that the actual calculation of the value of expression is postponed
until the value is I.
To see it in action, add a method
sub STORE {
my $obj = shift;
$#$obj = 1;
@$obj->[0,1] = ('=', shift);
}
to the package C. After this change one can do
my $a = symbolic->new(3);
my $b = symbolic->new(4);
my $c = sqrt($a**2 + $b**2);
and the numeric value of $c becomes 5. However, after calling
$a->STORE(12); $b->STORE(5);
the numeric value of $c becomes 13. There is no doubt now that the module
symbolic provides a I calculator indeed.
To hide the rough edges under the hood, provide a tie()d interface to the
package C. Add methods
sub TIESCALAR { my $pack = shift; $pack->new(@_) }
sub FETCH { shift }
sub nop { } # Around a bug
(the bug, fixed in Perl 5.14, is described in L<"BUGS">). One can use this
new interface as
tie $a, 'symbolic', 3;
tie $b, 'symbolic', 4;
$a->nop; $b->nop; # Around a bug
my $c = sqrt($a**2 + $b**2);
Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
of $c becomes 13. To insulate the user of the module add a method
sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
Now
my ($a, $b);
symbolic->vars($a, $b);
my $c = sqrt($a**2 + $b**2);
$a = 3; $b = 4;
printf "c5 %s=%f\n", $c, $c;
$a = 12; $b = 5;
printf "c13 %s=%f\n", $c, $c;
shows that the numeric value of $c follows changes to the values of $a
and $b.
=head1 AUTHOR
Ilya Zakharevich EFE.
=head1 SEE ALSO
The C pragma can be used to enable or disable overloaded
operations within a lexical scope - see L.
=head1 DIAGNOSTICS
When Perl is run with the B<-Do> switch or its equivalent, overloading
induces diagnostic messages.
Using the C command of Perl debugger (see L) one can
deduce which operations are overloaded (and which ancestor triggers
this overloading). Say, if C is overloaded, then the method C<(eq>
is shown by debugger. The method C<()> corresponds to the C
key (in fact a presence of this method shows that this package has
overloading enabled, and it is what is used by the C
function of module C).
The module might issue the following warnings:
=over 4
=item Odd number of arguments for overload::constant
(W) The call to overload::constant contained an odd number of arguments.
The arguments should come in pairs.
=item '%s' is not an overloadable type
(W) You tried to overload a constant type the overload package is unaware of.
=item '%s' is not a code reference
(W) The second (fourth, sixth, ...) argument of overload::constant needs
to be a code reference. Either an anonymous subroutine, or a reference
to a subroutine.
=item overload arg '%s' is invalid
(W) C was passed an argument it did not
recognize. Did you mistype an operator?
=back
=head1 BUGS AND PITFALLS
=over
=item *
A pitfall when fallback is TRUE and Perl resorts to a built-in
implementation of an operator is that some operators have more
than one semantic, for example C<|>:
use overload '0+' => sub { $_[0]->{n}; },
fallback => 1;
my $x = bless { n => 4 }, "main";
my $y = bless { n => 8 }, "main";
print $x | $y, "\n";
You might expect this to output "12".
In fact, it prints "<": the ASCII result of treating "|"
as a bitwise string operator - that is, the result of treating
the operands as the strings "4" and "8" rather than numbers.
The fact that numify (C<0+>) is implemented but stringify
(C<"">) isn't makes no difference since the latter is simply
autogenerated from the former.
The only way to change this is to provide your own subroutine
for C<'|'>.
=item *
Magic autogeneration increases the potential for inadvertently
creating self-referential structures.
Currently Perl will not free self-referential
structures until cycles are explicitly broken.
For example,
use overload '+' => 'add';
sub add { bless [ \$_[0], \$_[1] ] };
is asking for trouble, since
$obj += $y;
will effectively become
$obj = add($obj, $y, undef);
with the same result as
$obj = [\$obj, \$foo];
Even if no I assignment-variants of operators are present in
the script, they may be generated by the optimizer.
For example,
"obj = $obj\n"
may be optimized to
my $tmp = 'obj = ' . $obj; $tmp .= "\n";
=item *
The symbol table is filled with names looking like line-noise.
=item *
This bug was fixed in Perl 5.18, but may still trip you up if you are using
older versions:
For the purpose of inheritance every overloaded package behaves as if
C is present (possibly undefined). This may create
interesting effects if some package is not overloaded, but inherits
from two overloaded packages.
=item *
Before Perl 5.14, the relation between overloading and tie()ing was broken.
Overloading was triggered or not based on the I class of the
tie()d variable.
This happened because the presence of overloading was checked
too early, before any tie()d access was attempted. If the
class of the value FETCH()ed from the tied variable does not
change, a simple workaround for code that is to run on older Perl
versions is to access the value (via C<() = $foo> or some such)
immediately after tie()ing, so that after this call the I class
coincides with the current one.
=item *
Barewords are not covered by overloaded string constants.
=item *
The range operator C<..> cannot be overloaded.
=back
=cut
Simpan