Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Number::Complex;
- use Scalar::Util qw(looks_like_number);
- use Carp qw(croak);
- use Moo;
- use overload
- '+' => \&plus,
- '-' => \&minus,
- '""' => \&to_string;
- use namespace::sweep;
- has 'real' => (
- is => 'ro',
- isa => sub {
- my $item = shift;
- croak "$item is not a number" unless looks_like_number $item;
- },
- default => 0,
- writer => '_set_real',
- );
- has 'imag' => (
- is => 'ro',
- isa => sub {
- my $item = shift;
- croak "$item is not a number" unless looks_like_number $item;
- },
- default => 0,
- writer => '_set_imag',
- );
- around 'BUILDARGS' => sub {
- my $orig = shift;
- my $class = shift;
- if (@_ == 2) {
- my ($real, $imag) = @_;
- return $class->$orig(real => $real, imag => $imag);
- }
- else {
- return $class->$orig(@_);
- }
- };
- sub plus {
- my ($self, $other, $swap) = @_;
- my $class = ref $self;
- my $result = $class->new();
- if (!$swap and ref $other) {
- $result->_set_real($self->real() + $other->real());
- $result->_set_imag($self->imag() + $other->imag());
- }
- else {
- $result->_set_real($self->real() + $other);
- $result->_set_imag($self->imag());
- }
- return $result;
- }
- sub minus {
- my ($self, $other, $swap) = @_;
- my $class = ref $self;
- my $result = $class->new();
- if (!$swap and ref $other) {
- $result->_set_real($self->real() - $other->real());
- $result->_set_imag($self->imag() - $other->imag());
- }
- elsif (!$swap) {
- $result->_set_real($self->real() - $other);
- $result->_set_imag($self->imag());
- }
- else {
- $result->_set_real($other - $self->real());
- $result->_set_imag(-$self->imag());
- }
- return $result;
- }
- sub to_string {
- my $self = shift;
- my $real_str = $self->real();
- my $imag_str = $self->imag() >= 0
- ? "+" . $self->imag() : $self->imag();
- return sprintf "%s%si", $real_str, $imag_str;
- }
- __PACKAGE__->meta->make_immutable;
- unless (caller) {
- package main;
- use feature qw(say);
- my $a = Number::Complex->new(3, 4);
- my $b = Number::Complex->new(4, 3);
- say $a + $b;
- say $a + 2;
- say 2 + $a;
- say $a - $b;
- say $a - 2;
- say 2 - $a;
- }
- 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement