Element-wise operations: Difference between revisions
→{{header|Perl}}: re-write as one runnable file, use modern Perl
(→{{header|Vlang}}: Rename "Vlang" in "V (Vlang)") |
SqrtNegInf (talk | contribs) (→{{header|Perl}}: re-write as one runnable file, use modern Perl) |
||
Line 2,873:
This example demonstrates Perl's operator overload ability and bulk list operations using <tt>map</tt>.
use overload
'
'
'
'
'
sub new ($class, $value) { bless $value, ref $class || $class }
sub add {
sub sub {
sub mul {
sub div {
sub exp {
package main;
▲sub add { new Elementwise ref($_[1]) ? [map { $_[0][$_] + $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] + $_[1] } 0 .. $#{$_[0]} ] }
▲sub sub { new Elementwise ref($_[1]) ? [map { $_[0][$_] - $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] - $_[1] } 0 .. $#{$_[0]} ] }
▲sub mul { new Elementwise ref($_[1]) ? [map { $_[0][$_] * $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] * $_[1] } 0 .. $#{$_[0]} ] }
▲sub div { new Elementwise ref($_[1]) ? [map { $_[0][$_] / $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] / $_[1] } 0 .. $#{$_[0]} ] }
▲sub exp { new Elementwise ref($_[1]) ? [map { $_[0][$_] ** $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] ** $_[1] } 0 .. $#{$_[0]} ] }
$a = Elementwise->new([<1 2 3 4 5 6 7 8 9>]);
say <<"END";
a @$a▼
▲<syntaxhighlight lang="perl">use Elementwise;
▲a @$a
a OP a
+ @{$a+$a}
Line 2,924 ⟶ 2,904:
* @{$a*$a}
/ @{$a/$a}
a OP 5
+ @{$a+5}
Line 2,930 ⟶ 2,911:
* @{$a*5}
/ @{$a/5}
{{out}}
<pre>a 1 2 3 4 5 6 7 8 9
a OP a
+ 2 4 6 8 10 12 14 16 18
Line 2,940 ⟶ 2,922:
* 1 4 9 16 25 36 49 64 81
/ 1 1 1 1 1 1 1 1 1
a OP 5
+ 6 7 8 9 10 11 12 13 14
Line 2,946 ⟶ 2,929:
* 5 10 15 20 25 30 35 40 45
/ 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8
=={{header|Phix}}==
|