List comprehensions: Difference between revisions

→‎Perl: new example
m (→‎{{header|Erlang}}: optimized, made more idiomatic in syntax.)
(→‎Perl: new example)
Line 106:
 
 
 
=={{header|Perl}}==
 
Perl 5 does not have built-in list comprehension syntax. The closest approach are the list <code>map</code> and <code>grep</code> (elsewhere often known as filter) operators:
 
<lang perl>sub triples ($) {
my ($n) = @_;
map { my $x = $_; map { my $y = $_; map { [$x, $y, $_] } grep { $x**2 + $y**2 == $_**2 } 1..$n } 1..$n } 1..$n;
}</lang>
 
<code>map</code> binds <code>$_</code> to each element of the input list and collects the results from the block. <code>grep</code> returns every element of the input list for which the block returns true. The <code>..</code> operator generates a list of numbers in a specific range.
 
<lang perl>for my $t (triples(10)) {
print "@$t\n";
}</lang>
 
=={{header|Python}}==