RosettaCodeData/Task/Element-wise-operations/Perl/element-wise-operations.pl

41 lines
1.1 KiB
Perl

use v5.36;
package Elementwise;
use overload
'+' => sub ($a,$b,$) { $a->add($b) },
'-' => sub ($a,$b,$) { $a->sub($b) },
'*' => sub ($a,$b,$) { $a->mul($b) },
'/' => sub ($a,$b,$) { $a->div($b) },
'**' => sub ($a,$b,$) { $a->exp($b) };
sub new ($class, $value) { bless $value, ref $class || $class }
sub add { ref($_[1]) ? [map { $_[0][$_] + $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] + $_[1] } 0 .. $#{$_[0]} ] }
sub sub { ref($_[1]) ? [map { $_[0][$_] - $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] - $_[1] } 0 .. $#{$_[0]} ] }
sub mul { ref($_[1]) ? [map { $_[0][$_] * $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] * $_[1] } 0 .. $#{$_[0]} ] }
sub div { ref($_[1]) ? [map { $_[0][$_] / $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] / $_[1] } 0 .. $#{$_[0]} ] }
sub exp { ref($_[1]) ? [map { $_[0][$_] ** $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] ** $_[1] } 0 .. $#{$_[0]} ] }
package main;
$a = Elementwise->new([<1 2 3 4 5 6 7 8 9>]);
say <<"END";
a @$a
a OP a
+ @{$a+$a}
- @{$a-$a}
* @{$a*$a}
/ @{$a/$a}
** @{$a**$a}
a OP 5
+ @{$a+5}
- @{$a-5}
* @{$a*5}
/ @{$a/5}
** @{$a**5}
END