Vector: Difference between revisions

41 bytes removed ,  1 year ago
m
→‎{{header|Perl}}: do the same job, but less verbosely
m (→‎{{header|Perl}}: do the same job, but less verbosely)
Line 2,090:
=={{header|Perl}}==
Typically we would use a module, such as [https://metacpan.org/pod/Math::Vector::Real Math::Vector::Real] or [https://metacpan.org/pod/Math::Complex Math::Complex]. Here is a very basic Moose class.
<syntaxhighlight lang="perl">packageuse Vectorv5.36;
use Moose;
use feature 'say';
 
package Vector;
use overload '+' => \&add,
use Moose;
'-' => \&sub,
use overload '*+' => \&muladd,
'/-' => \&divsub,
'-*' => \&submul,
'/' => \&div,
'""' => \&stringify;
 
Line 2,103:
has 'y' => (is =>'rw', isa => 'Num', required => 1);
 
sub add ($a, $b, $) { Vector->new( x => $a->x -+ $b->x, y => $a->y -+ $b->y); }
sub add {
sub sub ($a, $b, $) { Vector->new( x => $a->x *- $b->x, y => $a->y *- $b->y); }
my($a, $b) = @_;
sub mul ($a, $b, $) { Vector->new( x => $a->x +* $b->x, y => $a->y +* $b->y); }
sub div ($a, $b, $) { Vector->new( x => $a->x / $b, y => $a->y / $b); }
}
sub stringify "("$self, $, $) { '(' . $self->x . "',"' . $self->y . ')'; }
sub sub {
my($a, $b) = @_;
Vector->new( x => $a->x - $b->x, y => $a->y - $b->y);
}
sub mul {
my($a, $b) = @_;
Vector->new( x => $a->x * $b, y => $a->y * $b);
}
sub div {
my($a, $b) = @_;
Vector->new( x => $a->x / $b, y => $a->y / $b);
}
sub stringify {
my $self = shift;
"(" . $self->x . "," . $self->y . ')';
}
 
package main;
2,392

edits