Overloaded operators: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (→‎{{header|Perl}}: revise code layout to emphasize parallelism)
Line 458: Line 458:
so that they can be used on members of that class(package). Also see 'Zeckendorf arithmetic' where overloading
so that they can be used on members of that class(package). Also see 'Zeckendorf arithmetic' where overloading
is used on Zeckendorf numbers.
is used on Zeckendorf numbers.
<syntaxhighlight lang="perl">#!/usr/bin/perl
<syntaxhighlight lang="perl">use v5.36;

use strict; # https://rosettacode.org/wiki/Overloaded_operators
use warnings;

my $x = Ones->new( 15 );
my $y = Ones->new( 4 );

my $z = $x + $y;
print "$x + $y = $z\n";
$z = $x - $y;
print "$x - $y = $z\n";
$z = $x * $y;
print "$x * $y = $z\n";
$z = $x / $y;
print "$x / $y = $z\n";


package Ones;
package Ones;
use overload qw("" asstring + add - subtract * multiply / divide);
use overload qw("" asstring + add - subtract * multiply / divide);


sub new ( $class, $value ) { bless \('1' x $value), ref $class || $class }
sub new
sub asstring ($self, $other, $) { $$self }
{
sub asdecimal ($self, $other, $) { length $$self }
my ( $class, $value ) = @_;
bless \('1' x $value), ref $class || $class;
sub add ($self, $other, $) { bless \($$self . $$other), ref $self }
sub subtract ($self, $other, $) { bless \($$self =~ s/$$other//r), ref $self }
}
sub multiply ($self, $other, $) { bless \($$self =~ s/1/$$other/gr), ref $self }

sub divide ($self, $other, $) { $self->new( $$self =~ s/$$other/$$other/g ) }
sub asstring
{
my ($self, $other, $swap) = @_;
$$self;
}

sub asdecimal
{
my ($self, $other, $swap) = @_;
length $$self;
}

sub add
{
my ($self, $other, $swap) = @_;
bless \($$self . $$other), ref $self;
}

sub subtract
{
my ($self, $other, $swap) = @_;
bless \($$self =~ s/$$other//r), ref $self;
}


package main;
sub multiply
{
my ($self, $other, $swap) = @_;
bless \($$self =~ s/1/$$other/gr), ref $self;
}


my($x,$y,$z) = ( Ones->new(15), Ones->new(4) );
sub divide
$z = $x + $y; say "$x + $y = $z";
{
my ($self, $other, $swap) = @_;
$z = $x - $y; say "$x - $y = $z";
$z = $x * $y; say "$x * $y = $z";
$self->new( $$self =~ s/$$other/$$other/g );
}</syntaxhighlight>
$z = $x / $y; say "$x / $y = $z";</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>