Jump to content

Element-wise operations: Difference between revisions

m
→‎{{header|Perl 6}}: added custom infix op, revised output format
m (→‎{{header|Perl 6}}: added custom infix op, revised output format)
Line 1,130:
 
=={{header|Perl 6}}==
{{Works with|rakudo|2016.05}}
Perl 6 already implements this and other metaoperators as higher-order functions (cross, zip, reduce, triangle, etc.) that are usually accessed through a meta-operator syntactic sugar that is productive over all appropriate operators, including user-defined ones. In this case, a dwimmy element-wise operator (generically known as a "hyper") is indicated by surrounding the operator with double angle quotes. Hypers dwim on the pointy end with cyclic APL semantics as necessary. You can turn the quote the other way to suppress dwimmery on that end. In this case we could have used <tt>»op»</tt> instead of <tt>«op»</tt> since the short side is always on the right.<lang perl6>my @a =
[1,2,3],
Line 1,136 ⟶ 1,137:
 
sub msay(@x) {
.perl.say for @x; -> @row {
print ' ', $_%1 ?? $_.nude.join('/') !! $_ for @row;
say '';
}
say '';
}
Line 1,153 ⟶ 1,157:
msay @a «/» 2;</lang>
{{out}}
<pre>[ 2, 4, 6]
[ 8, 10, 12]
[ 14, 16, 18]
 
[ 0, 0, 0]
[ 0, 0, 0]
[ 0, 0, 0]
 
[ 1, 4, 9]
[ 16, 25, 36]
[ 49, 64, 81]
 
[ 1/1, 1/1, 1/1]
[ 1/1, 1/1, 1/1]
[ 1/1, 1/1, 1/1]
 
[ 2, 3, 4]
[ 6, 7, 8]
[ 10, 11, 12]
 
[ 0, 1, 2]
[ 2, 3, 4]
[ 4, 5, 6]
 
[ 1, 2, 3]
[ 8, 10, 12]
[ 21, 24, 27]
 
[ 1/1, 2/1, 3/1]
[ 2/1, 5/2, 3/1]
[ 7/3, 8/3, 3/1]
 
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]
 
[ -1, 0, 1]
[ 2, 3, 4]
[ 5, 6, 7]
 
[ 2, 4, 6]
[ 8, 10, 12]
[ 14, 16, 18]
 
[ 1/2, 1/1, 3/2]
[ 2/1, 5/2, 3/1]
[ 7/2, 4/1, 9/2]</pre>
In addition to calling the underlying higher-order functions directly, it's supposed to be possible to name a function like <tt>&[«+»]</tt> to get the first example above, but this is currently (2012-08) supported only be niecza.
 
<lang perl6>sub infix:<M+> (\l,\r) { l <<+>> r }
 
msay @a M+ @a;
msay @a M+ [1,2,3];
msay @a M+ 2;</lang>
{{out}}
<pre> 2 4 6
8 10 12
14 16 18
 
2 3 4
6 7 8
10 11 12
 
3 4 5
6 7 8
9 10 11</pre>
 
=={{header|PicoLisp}}==
2,392

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.