List comprehensions: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎horizontal list: added a SAY.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(23 intermediate revisions by 13 users not shown)
Line 17:
If the language has multiple ways for expressing such a construct (for example, direct list comprehensions and generators), write one example for each.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
print(cart_product(1..20, 1..20, 1..20).filter((x, y, z) -> x ^ 2 + y ^ 2 == z ^ 2 & y C x .. z))
 
{{out}}
<pre>
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
</pre>
 
=={{header|ABAP}}==
 
<syntaxhighlight lang="abap">
<lang ABAP>
CLASS lcl_pythagorean_triplet DEFINITION CREATE PUBLIC.
PUBLIC SECTION.
Line 68 ⟶ 78:
START-OF-SELECTION.
cl_demo_output=>display( lcl_pythagorean_triplet=>get_triplets( n = 20 ) ).
</syntaxhighlight>
</lang>
{{out}}
Line 85 ⟶ 95:
There is no equivalent construct in Ada. In Ada05, the predefined library Ada.Containers
implements 3 types of Doubly_Linked_Lists : Basic; Indefinite; Restricted.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
 
Line 130 ⟶ 140:
end loop;
end Pythagore_Set;
</syntaxhighlight>
</lang>
 
program output:
Line 147 ⟶ 157:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">MODE XYZ = STRUCT(INT x,y,z);
 
OP +:= = (REF FLEX[]XYZ lhs, XYZ rhs)FLEX[]XYZ: (
Line 161 ⟶ 171:
FOR x TO n DO FOR y FROM x+1 TO n DO FOR z FROM y+1 TO n DO IF x*x + y*y = z*z THEN xyz +:= XYZ(x,y,z) FI OD OD OD;
xyz), new line
))</langsyntaxhighlight>
Output:
<div style="width:full;overflow:scroll"><pre>
Line 172 ⟶ 182:
 
{{trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- List comprehension by direct and unsugared use of list monad
 
-- pythagoreanTriples :: Int -> [(Int, Int, Int)]
Line 263 ⟶ 273:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<lang AppleScriptpre>{{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, {9, 12, 15}, {12, 16, 20}, {15, 20, 25}}</langpre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets</syntaxhighlight>
 
{{out}}
 
<pre>[3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20]</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
List Comprehension is not built in. <langsyntaxhighlight AutoHotkeylang="autohotkey">
comprehend("show", range(1, 20), "triples")
return
Line 338 ⟶ 364:
return set
}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
Bracmat does not have built-in list comprehension, but nevertheless there is a solution for fixed n that does not employ explicit loop syntax. By their positions in the pattern and the monotonically increasing values in the subject, it is guaranteed that <code>x</code> always is smaller than <code>y</code> and that <code>y</code> always is smaller than <code>z</code>. The combination of flags <code>%@</code> ensures that <code>x</code>, <code>y</code> and <code>z</code> pick minimally one (<code>%</code>) and at most one (<code>@</code>) element from the subject list.
<langsyntaxhighlight lang="bracmat">
:?py { Initialize the accumulating result list. }
& ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { This is the subject }
Line 358 ⟶ 384:
| out$!py { You get here when backtracking has
exhausted all combinations of x, y and z }
);</langsyntaxhighlight>
Output:
<pre> (12,16,20)
Line 371 ⟶ 397:
C doesn't have a built-in syntax for this, but any problem can be solved if you throw enough macros at it:
{{works with|GCC}}
The program below is C11 compliant. For C99 compilers note the change on line 57 :(output remains unchanged).
<syntaxhighlight lang="c">
<lang C>
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
</lang>
to
<lang C>
int i;
for (i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
</lang>
Output remains unchanged.
<lang c>
#include <stdlib.h>
#include <stdio.h>
Line 438 ⟶ 455:
List * intRangeList(int f, int t) {
List * l = listNew(sizeof f, &f), * e = l;
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); } // C11 compliant
//int i;
//for (i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); } // use this for C99
return l;
}
Line 460 ⟶ 479:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>3, 4, 5
Line 474 ⟶ 493:
=={{header|C sharp|C#}}==
===LINQ===
<langsyntaxhighlight lang="csharp">using System.Linq;
 
static class Program
Line 491 ⟶ 510:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
There is no equivalent construct in C++. The code below uses two nested loops and an ''if'' statement:
 
<langsyntaxhighlight lang="cpp">#include <vector>
#include <cmath>
#include <iostream>
Line 527 ⟶ 546:
}
}
</syntaxhighlight>
</lang>
 
This produces the following output:
Line 534 ⟶ 553:
{{works with|C++11}}
 
<langsyntaxhighlight lang="cpp">#include <functional>
#include <iostream>
 
Line 557 ⟶ 576:
});
return 0;
}</langsyntaxhighlight>
 
Output:
Line 569 ⟶ 588:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">flatten = (arr) -> arr.reduce ((memo, b) -> memo.concat b), []
 
pyth = (n) ->
Line 585 ⟶ 604:
[x, y, z]
))
# pyth can also be written more concisely as
# pyth = (n) -> flatten (flatten ([x, y, z] for z in [y..n] when x*x + y*y is z*z for y in [x..n]) for x in [1..n])
 
console.dir pyth 20</langsyntaxhighlight>
 
<code>pyth</code> can also be written more concisely as
 
<lang coffeescript>pyth = (n) -> flatten (flatten ([x, y, z] for z in [y..n] when x*x + y*y is z*z for y in [x..n]) for x in [1..n])</lang>
 
=={{header|Common Lisp}}==
Line 597 ⟶ 614:
Here are the Pythagorean triples:
 
<langsyntaxhighlight lang="lisp">(defun pythagorean-triples (n)
(loop for x from 1 to n
append (loop for y from x to n
append (loop for z from y to n
when (= (+ (* x x) (* y y)) (* z z))
collect (list x y z)))))</langsyntaxhighlight>
 
We can also define a new macro for list comprehensions. We can implement them easily with the help of the <code>iterate</code> package.
 
<langsyntaxhighlight lang="lisp">(defun nest (l)
(if (cdr l)
`(,@(car l) ,(nest (cdr l)))
Line 620 ⟶ 637:
`((iter ,outer ,form)
,@(mapcar #'desugar-listc-form forms)
(in ,outer (collect ,expr)))))</langsyntaxhighlight>
 
We can then define a function to compute Pythagorean triples as follows:
 
<langsyntaxhighlight lang="lisp">(defun pythagorean-triples (n)
(listc (list x y z)
(for x from 1 to n)
(for y from x to n)
(for z from y to n)
(when (= (+ (expt x 2) (expt y 2)) (expt z 2)))))</langsyntaxhighlight>
 
=={{header|D}}==
D doesn't have list comprehensions. One implementation:
<langsyntaxhighlight lang="d">import std.stdio, std.typetuplemeta, std.range;
 
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
Line 642 ⟶ 659:
lazy TP where) {
Appender!(TA[]) result;
auto iters = TypeTupleAliasSeq!(iter1, iter2, iter3);
 
foreach (el1; items1) {
Line 656 ⟶ 673:
}
 
TypeTupleAliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
Line 666 ⟶ 683:
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}</langsyntaxhighlight>
{{out}}
<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]]</pre>
Line 672 ⟶ 689:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator") # considered experimental
 
accum [] for x in 1..n { for y in x..n { for z in y..n { if (x**2 + y**2 <=> z**2) { _.with([x,y,z]) } } } }</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; copied from Racket
 
Line 686 ⟶ 703:
(list x y z))
→ ((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))
</syntaxhighlight>
</lang>
 
=={{header|Efene}}==
 
<langsyntaxhighlight lang="efene">pythag = fn (N) {
[(A, B, C) for A in lists.seq(1, N) \
for B in lists.seq(A, N) \
Line 701 ⟶ 718:
io.format("~p~n", [pythag(20)])
}
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">pyth n = [(x,y,z) \\ x <- [1..n], y <- [x..n], z <- [y..n] | x**2 + y**2 == z**2]</langsyntaxhighlight>
 
=={{header|Elixir}}==
Line 719 ⟶ 736:
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]</langsyntaxhighlight>
 
=={{header|Factor}}==
Factor does not support list comprehensions by default. The <code>backtrack</code> vocabulary can make for a faithful imitation, however.
<langsyntaxhighlight lang="factor">USING: backtrack kernel locals math math.ranges ;
 
:: pythagorean-triples ( n -- seq )
Line 742 ⟶ 759:
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
 
Complex numbers simplify the task. However, the reshape intrinsic function along with implicit do loops can generate high rank matrices.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun 7 23:39:20
Line 779 ⟶ 796:
print '(3i4)',d(:,:i)
end program list_comprehension
</syntaxhighlight>
</lang>
 
 
Line 785 ⟶ 802:
{{trans|Run BASIC}}
FreeBASIC no tiene listas de comprensión. Una implementación:
<langsyntaxhighlight lang="freebasic">Dim As Integer x, y, z, n = 25
For x = 1 To n
For y = x To n
Line 793 ⟶ 810:
Next y
Next x
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 808 ⟶ 825:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def triples( n ) = [(a, b, c) | a <- 1..n-2, b <- a+1..n-1, c <- b+1..n if a^2 + b^2 == c^2]
 
println( triples(20) )</langsyntaxhighlight>
 
{{out}}
Line 819 ⟶ 836:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># We keep only primitive pythagorean triples
pyth := n ->
Filtered(Cartesian([1 .. n], [1 .. n], [1 .. n]),
Line 828 ⟶ 845:
# [ [ 3, 4, 5 ], [ 5, 12, 13 ], [ 7, 24, 25 ], [ 8, 15, 17 ], [ 9, 40, 41 ], [ 11, 60, 61 ], [ 12, 35, 37 ],
# [ 13, 84, 85 ], [ 16, 63, 65 ], [ 20, 21, 29 ], [ 28, 45, 53 ], [ 33, 56, 65 ], [ 36, 77, 85 ], [ 39, 80, 89 ],
# [ 48, 55, 73 ], [ 65, 72, 97 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
Go doesn't have special syntax for list comprehensions but we can build a function which behaves similarly.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 893 ⟶ 910:
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}</langsyntaxhighlight>
 
{{out}}
Line 901 ⟶ 918:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
Line 907 ⟶ 924:
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]</langsyntaxhighlight>
 
List-comprehensions and do notation are two alternative and equivalent forms of syntactic sugar in Haskell.
Line 913 ⟶ 930:
The list comprehension above could be re-sugared in Do notation as:
 
<langsyntaxhighlight lang="haskell">pyth :: Int -> [(Int, Int, Int)]
pyth n = do
x <- [1 .. n]
Line 920 ⟶ 937:
if x ^ 2 + y ^ 2 == z ^ 2
then [(x, y, z)]
else []</langsyntaxhighlight>
 
and both of the above could be de-sugared to:
<langsyntaxhighlight lang="haskell">pyth :: Int -> [(Int, Int, Int)]
pyth n =
[1 .. n] >>=
Line 933 ⟶ 950:
case x ^ 2 + y ^ 2 == z ^ 2 of
True -> [(x, y, z)]
_ -> []</langsyntaxhighlight>
 
which can be further specialised (given the particular context of the list monad,
Line 939 ⟶ 956:
in which (>>=) is flip concatMap, pure is flip (:) [], and empty is []) to:
 
<langsyntaxhighlight lang="haskell">pyth :: Int -> [(Int, Int, Int)]
pyth n =
concatMap
Line 955 ⟶ 972:
 
main :: IO ()
main = print $ pyth 25</langsyntaxhighlight>
{{Out}}
<pre>[(3,4,5),(5,12,13),(6,8,10),(7,24,25),(8,15,17),(9,12,15),(12,16,20),(15,20,25)]</pre>
Line 961 ⟶ 978:
Finally an alternative to the list comprehension from the beginning. First introduce all triplets:
 
<langsyntaxhighlight lang="haskell">triplets n = [(x, y, z) | x <- [1 .. n], y <- [x .. n], z <- [y .. n]]</langsyntaxhighlight>
 
If we apply this to our list comprehension we get this tidy line of code:
 
<langsyntaxhighlight lang="haskell">[(x, y, z) | (x, y, z) <- triplets n, x^2 + y^2 == z^2]</langsyntaxhighlight>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="clojure">(defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
Line 977 ⟶ 994:
 
(print (triples 15))
; [(3, 4, 5), (5, 12, 13), (6, 8, 10), (9, 12, 15)]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|uniconUnicon}} ==
 
Icon's (and Unicon's) natural goal-directly evaluation produces result
Line 985 ⟶ 1,002:
expression:
 
<langsyntaxhighlight lang="unicon">
|(x := seq(), x^2 > 3, x*2)
</syntaxhighlight>
</lang>
 
is capable of producing successive elements from the infinite list described in the
Wikipedia article. For example, to produce the first 100 elements:
 
<langsyntaxhighlight lang="unicon">
procedure main()
every write(|(x := seq(), x^2 > 3, x*2) \ 100
end
</syntaxhighlight>
</lang>
 
While result sequences are lexically bound to the code that describes them,
Line 1,003 ⟶ 1,020:
with (works in both languages):
 
<langsyntaxhighlight lang="unicon">procedure main(a)
n := integer(!a) | 20
s := create (x := 1 to n, y := x to n, z := y to n, x^2+y^2 = z^2, [x,y,z])
while a := @s do write(a[1]," ",a[2]," ",a[3])
end</langsyntaxhighlight>
 
Sample output:
Line 1,019 ⟶ 1,036:
12 16 20
->
</pre>
 
=={{header|Insitux}}==
 
{{Trans|Clojure}}
 
<syntaxhighlight lang="insitux">
(function pythagorean-triples n
(let n+1 (inc n))
(for x (range 1 n+1)
y (range x n+1)
z (range y n+1)
(unless (= (+ (* x x) (* y y)) (* z z))
(continue))
[x y z]))
 
(pythagorean-triples 20)
</syntaxhighlight>
{{out}}
<pre>
[[3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20]]
</pre>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke">for(
x <- 1..20,
y <- x..20,
Line 1,028 ⟶ 1,066:
x * x + y * y == z * z,
[x, y, z]
)</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j">require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth</langsyntaxhighlight>
 
The idiom here has two major elements:
Line 1,051 ⟶ 1,089:
Example use:
 
<langsyntaxhighlight Jlang="j"> pythTr 20
3 4 5
5 12 13
Line 1,057 ⟶ 1,095:
8 15 17
9 12 15
12 16 20</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,063 ⟶ 1,101:
 
Using list-of-arrays made the syntax easier than list-of-lists, but meant that you need the "output expression" part to get to something easily printable.
<langsyntaxhighlight Javalang="java">// Boilerplate
import java.util.Arrays;
import java.util.List;
Line 1,096 ⟶ 1,134:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15]]</pre>
Line 1,106 ⟶ 1,144:
ES5 does not provide built-in notation for list comprehensions. The list monad pattern which underlies list comprehension notation can, however, be used in any language which supports the use of higher order functions. The following shows how we can achieve the same result by directly using a list monad in ES5, without the abbreviating convenience of any specific syntactic sugar.
 
<langsyntaxhighlight lang="javascript">// USING A LIST MONAD DIRECTLY, WITHOUT SPECIAL SYNTAX FOR LIST COMPREHENSIONS
 
(function (n) {
Line 1,137 ⟶ 1,175:
}
 
})(100);</langsyntaxhighlight>
 
Output:
Line 1,150 ⟶ 1,188:
See [https://developer.mozilla.org/en/New_in_JavaScript_1.7#Array_comprehensions here] for more details
 
<langsyntaxhighlight lang="javascript">function range(begin, end) {
for (let i = begin; i < end; ++i)
yield i;
Line 1,166 ⟶ 1,204:
 
for each(var triple in triples(20))
print(triple);</langsyntaxhighlight>
 
outputs:
Line 1,184 ⟶ 1,222:
by using <code>concatMap</code> (the monadic bind function for lists), and <code>x => [x]</code> (monadic pure/return for lists):
 
<langsyntaxhighlight JavaScriptlang="javascript">(n => {
'use strict';
 
Line 1,214 ⟶ 1,252:
enumFromTo(x, n)),
enumFromTo(1, n));
})(20);</langsyntaxhighlight>
 
Or, expressed in terms of bind (>>=)
 
<langsyntaxhighlight Javascriptlang="javascript">(n => {
'use strict';
 
Line 1,258 ⟶ 1,296:
)));
 
})(20);</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]]</langsyntaxhighlight>
 
=={{header|jq}}==
'''Direct approach''':<langsyntaxhighlight lang="jq">def triples(n):
range(1;n+1) as $x | range($x;n+1) as $y | range($y;n+1) as $z
| select($x*$x + $y*$y == $z*$z)
| [$x, $y, $z] ;
</syntaxhighlight>
</lang>
 
'''Using listof(stream; criterion)'''
<langsyntaxhighlight lang="jq"># listof( stream; criterion) constructs an array of those
# elements in the stream that satisfy the criterion
def listof( stream; criterion): [ stream|select(criterion) ];
Line 1,279 ⟶ 1,317:
.[0] * .[0] + .[1] * .[1] == .[2] * .[2] ) ;
 
listof_triples(20)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,289 ⟶ 1,327:
Array comprehension:
 
<syntaxhighlight lang="julia">
<lang Julia>
julia> n = 20
20
Line 1,301 ⟶ 1,339:
(9,12,15)
(12,16,20)
</syntaxhighlight>
</lang>
 
A Julia generator comprehension (note the outer round brackets), returns an iterator over the same result rather than an explicit array:
 
<syntaxhighlight lang="julia">
<lang Julia>
julia> ((x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2)
Base.Flatten{Base.Generator{UnitRange{Int64},##33#37}}(Base.Generator{UnitRange{Int64},##33#37}(#33,1:20))
Line 1,317 ⟶ 1,355:
(9,12,15)
(12,16,20)
</syntaxhighlight>
</lang>
 
Array comprehensions may also be N-dimensional, not just vectors:
 
<syntaxhighlight lang="julia">
<lang Julia>
julia> [i + j for i in 1:5, j in 1:5]
5×5 Array{Int64,2}:
Line 1,345 ⟶ 1,383:
5 6 7 8 9
6 7 8 9 10
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun pythagoreanTriples(n: Int) =
Line 1,361 ⟶ 1,399:
fun main(args: Array<String>) {
println(pythagoreanTriples(20))
}</langsyntaxhighlight>
 
{{out}}
Line 1,370 ⟶ 1,408:
=={{header|Lasso}}==
Lasso uses query expressions for list manipulation.
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
 
local(n = 20)
Line 1,380 ⟶ 1,418:
select (:#x, #y, #z)
)
#triples->join('\n')</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="lasso">staticarray(3, 4, 5)
staticarray(5, 12, 13)
staticarray(6, 8, 10)
staticarray(8, 15, 17)
staticarray(9, 12, 15)
staticarray(12, 16, 20)</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua doesn't have list comprehensions built in, but they can be constructed from chained coroutines:
 
<langsyntaxhighlight lang="lua">
LC={}
LC.__index = LC
Line 1,427 ⟶ 1,465:
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
</syntaxhighlight>
</lang>
 
We can then define a function to compute Pythagorean triples as follows:
 
<langsyntaxhighlight lang="lua">
function get(key)
return (function(arg) return arg[key] end)
Line 1,447 ⟶ 1,485:
print(arg.x, arg.y, arg.z)
end
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Select[Tuples[Range[100], 3], #1[[1]]^2 + #1[[2]]^2 == #1[[3]]^2 &]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="mathematica">Pick[#, (#^2).{1, 1, -1}, 0] &@Tuples[Range[100], 3]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
In Matlab/Octave, one does not think much about lists rather than vectors and matrices. Probably, the find() operation comes closes to the task
<langsyntaxhighlight Matlablang="matlab">N = 20
[a,b] = meshgrid(1:N, 1:N);
c = sqrt(a.^2 + b.^2);
[x,y] = find(c == fix(c));
disp([x, y, sqrt(x.^2 + y.^2)])</langsyntaxhighlight>
 
{{out}}
Line 1,485 ⟶ 1,523:
''Solutions'' behaves like list comprehension since compound goals resemble set-builder notation.
 
<langsyntaxhighlight lang="mercury">
:- module pythtrip.
:- interface.
Line 1,510 ⟶ 1,548:
solutions((pred(Triple::out) is nondet :- pythTrip(20,Triple)),Result),
write(Result,!IO).
</syntaxhighlight>
</lang>
 
=={{header|Nemerle}}==
Demonstrating a list comprehension and an iterator. List comprehension adapted from Haskell example, iterator adapted from C# example.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Collections.Generic;
Line 1,552 ⟶ 1,590:
}
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
 
There are no list comprehensions in Nim, but thanks to the strong metaprogramming capabilities we can implement our own:
List comprehension is done in the standard library with the collect() macro (which uses for-loop macros) from the sugar package:
<lang nim>import macros
<syntaxhighlight lang="nim">import sugar, math
 
let n = 20
let triplets = collect(newSeq):
for x in 1..n:
for y in x..n:
for z in y..n:
if x^2 + y^2 == z^2:
(x,y,z)
echo triplets</syntaxhighlight>
Output:
<pre>@[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]</pre>
 
A special syntax for list comprehensions in Nim can be implemented thanks to the strong metaprogramming capabilities:
<syntaxhighlight lang="nim">import macros
 
type ListComprehension = object
var lc*: ListComprehension
 
macro `[]`*(lc: ListComprehension, x, t): expruntyped =
expectLen(x, 3)
expectKind(x, nnkInfix)
expectKind(x[0], nnkIdent)
assert($x[0].identstrVal == "|")
 
result = newCall(
Line 1,577 ⟶ 1,630:
expectKind(y, nnkInfix)
expectMinLen(y, 1)
if y[0].kind == nnkIdent and $y[0].identstrVal == "<-":
expectLen(y, 3)
result = newNimNode(nnkForStmt).add(y[1], y[2], result)
Line 1,604 ⟶ 1,657:
 
const n = 20
echo lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]</syntaxhighlight>
tuple[a,b,c: int]]</lang>
Output:
<pre>@[(a: 3, b: 4, c: 5), (a: 5, b: 12, c: 13), (a: 6, b: 8, c: 10), (a: 8, b: 15, c: 17), (a: 9, b: 12, c: 15), (a: 12, b: 16, c: 20)]</pre>
Line 1,611 ⟶ 1,663:
=={{header|OCaml}}==
 
As of OCaml 4.08 (2019), [https://v2.ocaml.org/manual/bindingops.html binding operators] were added to the language syntax. A general notion of "comprehension syntax" can be recovered using them.
[http://batteries.forge.ocamlcore.org/ OCaml Batteries Included] has uniform comprehension syntax for lists, arrays, enumerations (like streams), lazy lists (like lists but evaluated on-demand), sets, hashtables, etc.
 
ComprehensionAssuming area comprehension is of the form
<code>[? expression | x <- enumeration ; condition; condition ; ... ]</code>
We can rewrite it using binding operators like so
<syntaxhighlight lang="ocaml">let* x = enumeration in
if not condition then empty else
return expression
</syntaxhighlight>
 
For instance, we can write the required Pythagorean triples comprehension:
For instance,
<lang ocaml># [? 2 * x | x <- 0 -- max_int ; x * x > 3];;
- : int Enum.t = <abstr></lang>
or, to compute a list,
<lang ocaml># [? List: 2 * x | x <- 0 -- 100 ; x * x > 3];;
- : int list = [2; 4; 6; 8; 10]</lang>
or, to compute a set,
<lang ocaml># [? PSet: 2 * x | x <- 0 -- 100 ; x * x > 3];;
- : int PSet.t = <abstr></lang>
 
<syntaxhighlight lang="ocaml">let pyth n =
etc..
let* x = 1 -- n in
let* y = x -- n in
let* z = y -- n in
if x * x + y * y <> z * z then [] else
[x, y, z]
</syntaxhighlight>
 
where the <code>(let*)</code> and <code>(--)</code> operators are defined for the <code>List</code> module like so:
A standard OCaml distribution also includes a number of camlp4 extensions, including one that provides list comprehensions:
 
<lang ocaml># #camlp4o;;
<syntaxhighlight lang="ocaml">let (let*) xs f = List.concat_map f xs
# #require "camlp4.listcomprehension";;
let (--) a b = List.init (b-a+1) ((+)a)
/home/user//.opam/4.06.1+trunk+flambda/lib/ocaml/camlp4/Camlp4Parsers/Camlp4ListComprehension.cmo: loaded
</syntaxhighlight>
# [ x * 2 | x <- [1;2;3;4] ];;
 
- : int list = [2; 4; 6; 8]
=====Historical note=====
# [ x * 2 | x <- [1;2;3;4]; x > 2 ];;
 
- : int list = [6; 8]</lang>
:OCaml never had a built-in list-comprehension syntax. However, there have been a couple of preprocessing syntax extensions which aimed to add list comprehensions sugar to the language. One of which was shipped directly with [https://github.com/camlp4/camlp4 camlp4], a tool for syntax extensions that was bundled with the OCaml compiler distribution, up to version 4.02 (2014), and was completely deprecated after version 4.08 (2019).
 
:Another, [https://github.com/ocaml-batteries-team/batteries-included OCaml Batteries Included], had uniform comprehension syntax for lists, arrays, enumerations (like streams), lazy lists (like lists but evaluated on-demand), sets, hashtables, etc. This later split into the now legacy package [https://github.com/murmour/pa_comprehension pa_comprehensions], which is similarly deprecated.
 
=={{header|Oz}}==
Line 1,642 ⟶ 1,700:
However, there is a list comprehension package available [http://oz-code.googlecode.com/files/ListComprehension.zip here]. It uses the <em>unofficial and deprecated</em> macro system. Usage example:
 
<langsyntaxhighlight lang="oz">functor
import
LazyList
Line 1,661 ⟶ 1,719:
 
{Application.exit 0}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
GP 2.6.0 added support for a new comprehension syntax:
{{works with|PARI/GP|2.6.0 and above}}
<langsyntaxhighlight lang="parigp">f(n)=[v|v<-vector(n^3,i,vector(3,j,i\n^(j-1)%n)),norml2(v)==2*v[3]^2]</langsyntaxhighlight>
 
Older versions of GP can emulate this through <code>select</code>:
{{PARI/GP select}}
<langsyntaxhighlight lang="parigp">f(n)=select(v->norml2(v)==2*v[3]^2,vector(n^3,i,vector(3,j,i\n^(j-1)%n)))</langsyntaxhighlight>
 
Version 2.4.2 (obsolete, but widespread on Windows systems) requires inversion:
{{works with|PARI/GP|2.4.2}}
<langsyntaxhighlight lang="parigp">f(n)=select(vector(n^3,i,vector(3,j,i\n^(j-1)%n)),v->norml2(v)==2*v[3]^2)</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 1,680 ⟶ 1,738:
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:
 
<langsyntaxhighlight 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;
}</langsyntaxhighlight>
 
<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.
 
<langsyntaxhighlight lang="perl">for my $t (triples(10)) {
print "@$t\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,701 ⟶ 1,759:
Thinking laterally, Phix also does not have any special syntax for dictionaries, instead they are supported
via an autoinclude with the following standard hll routines:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>global function new_dict(integer pool_only=0)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">pool_only</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
global procedure destroy_dict(integer tid, integer justclear=0)
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #7060A8;">destroy_dict</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">justclear</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
global procedure setd(object key, object data, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global function getd(object key, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global procedure destroy_dict(integer tid, integer justclear=0)
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #7060A8;">destroy_dict</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">justclear</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
global function getd_index(object key, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global function getd_by_index(integer node, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">getd_by_index</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">node</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global procedure deld(object key, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #7060A8;">deld</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global procedure traverse_dict(integer rid, object user_data=0, integer tid=1)
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">user_data</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
global function dict_size(integer tid=1)</lang>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">dict_size</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
Clearly it would be relatively trivial for the compiler, just like it does with s[i], to map some other new
dictionary syntax to calls to these routines (not that it would ever use the default tid of 1, and admittedly
Line 1,717 ⟶ 1,777:
 
With all that in mind, the following (which works just fine as it is) might be a first step to formal list comprehension support:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">-- demo\rosetta\List_comprehensions.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
-- ====================================
<span style="color: #008080;">function</span> <span style="color: #000000;">list_comprehension</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">level</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">args</span><span style="color: #0000FF;">={})</span>
--
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
function list_comprehension(sequence s, integer rid, integer nargs, integer level=1, sequence args={})
<span style="color: #000000;">args</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">0</span>
sequence res = {}
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
args &= 0
<span style="color: #000000;">args</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
for i=1 to length(s) do
<span style="color: #008080;">if</span> <span style="color: #000000;">level</span><span style="color: #0000FF;"><</span><span style="color: #000000;">k</span> <span style="color: #008080;">then</span>
args[$] = s[i]
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">list_comprehension</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">level</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">args</span><span style="color: #0000FF;">))</span>
if level<nargs then
<span style="color: #008080;">else</span>
res &= list_comprehension(s,rid,nargs,level+1,args)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">call_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res &= call_func(rid,args)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return res
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">triangle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;"><</span><span style="color: #000000;">b</span> <span style="color: #008080;">and</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">c</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span> <span style="color: #008080;">then</span>
function triangle(integer a, b, c)
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">}}</span>
if a<b and a*a+b*b=c*c then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return {{a,b,c}}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return {}
end function
<span style="color: #0000FF;">?</span><span style="color: #000000;">list_comprehension</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"triangle"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
 
<!--</syntaxhighlight>-->
?list_comprehension(tagset(20),routine_id("triangle"),3)</lang>
{{out}}
<pre>
{{3,4,5},{5,12,13},{6,8,10},{8,15,17},{9,12,15},{12,16,20}}
</pre>
 
=={{header|Picat}}==
===List comprehensions===
<syntaxhighlight lang="picat">pyth(N) = [[A,B,C] : A in 1..N, B in A..N, C in B..N, A**2 + B**2 == C**2].</syntaxhighlight>
 
===Array comprehensions===
Picat also has array comprehensions. Arrays are generally used for faster access (using <code>{}</code> instead of <code>[]</code>).
 
<syntaxhighlight lang="picat">pyth(N) = {{A,B,C} : A in 1..N, B in A..N, C in B..N, A**2 + B**2 == C**2}.</syntaxhighlight>
 
===findall/2===
A related construct is <code>findall/2</code> to get all solutions for the specific goal at the second parameter. Here this is shown with <code>member/2</code> for generating the numbers to test (which for this task is fairly inefficient).
<syntaxhighlight lang="text">pyth(N) = findall([A,B,C], (member(A,1..N), member(B,1..N), member(C,1..N), A < B, A**2 + B**2 == C**2)).</syntaxhighlight>
 
=={{header|PicoLisp}}==
Line 1,752 ⟶ 1,825:
We might use a generator function, pipe, coroutine or pilog predicate.
===Using a generator function===
<langsyntaxhighlight PicoLisplang="picolisp">(de pythag (N)
(job '((X . 1) (Y . 1) (Z . 0))
(loop
Line 1,764 ⟶ 1,837:
 
(while (pythag 20)
(println @) )</langsyntaxhighlight>
===Using a pipe===
<langsyntaxhighlight PicoLisplang="picolisp">(pipe
(for X 20
(for Y (range X 20)
Line 1,773 ⟶ 1,846:
(pr (list X Y Z)) ) ) ) )
(while (rd)
(println @) ) )</langsyntaxhighlight>
===Using a coroutine===
Coroutines are available only in the 64-bit version.
<langsyntaxhighlight PicoLisplang="picolisp">(de pythag (N)
(co 'pythag
(for X N
Line 1,785 ⟶ 1,858:
 
(while (pythag 20)
(println @) )</langsyntaxhighlight>
 
Output in all three cases:
Line 1,796 ⟶ 1,869:
===Using Pilog===
{{works with|PicoLisp|3.0.9.7}}
<langsyntaxhighlight PicoLisplang="picolisp">(be pythag (@N @X @Y @Z)
(for @X @N)
(for @Y @X @N)
Line 1,802 ⟶ 1,875:
(^ @
(let (X (-> @X) Y (-> @Y) Z (-> @Z))
(= (+ (* X X) (* Y Y)) (* Z Z)) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (? (pythag 20 @X @Y @Z))
@X=3 @Y=4 @Z=5
@X=5 @Y=12 @Z=13
Line 1,811 ⟶ 1,884:
@X=9 @Y=12 @Z=15
@X=12 @Y=16 @Z=20
-> NIL</langsyntaxhighlight>
 
=={{header|Prolog}}==
SWI-Prolog does not have list comprehension, however we can simulate it.
 
<langsyntaxhighlight Prologlang="prolog">% We need operators
:- op(700, xfx, <-).
:- op(450, xfx, ..).
Line 1,848 ⟶ 1,921:
Vs <- {Var & Dec} :-
findall(Var, maplist(call, [Dec]), Vs).
</syntaxhighlight>
</lang>
Examples of use :<BR>
List of Pythagorean triples :
Line 1,874 ⟶ 1,947:
 
=={{header|Python}}==
<syntaxhighlight lang="python">
List comprehension:
import itertools
 
n = 20
<lang python>[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]</lang>
 
A Python generator expression (note the outer round brackets), returns an iterator over the same result rather than an explicit list:
 
<lang python>((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2)</lang>
 
A slower but more readable version:
 
# List comprehension:
<lang python>[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z]</lang>
[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
 
# A Python generator expression (note the outer round brackets),
Or as an iterator:
# returns an iterator over the same result rather than an explicit list:
((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2)
 
# A slower but more readable version:
<lang python>((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z)</lang>
[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z]
 
# Or as an iterator:
Alternatively we shorten the initial list comprehension but this time without compromising on speed. First we introduce a generator which generates all triplets:
((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z)
 
# Alternatively we shorten the initial list comprehension but this time without compromising on speed.
<lang python>def triplets(n):
# First we introduce a generator which generates all triplets:
def triplets(n):
for x in xrange(1, n + 1):
for y in xrange(x, n + 1):
for z in xrange(y, n + 1):
yield x, y, z</lang>
 
# Apply this to our list comprehension gives:
[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2]
 
# Or as an iterator:
<lang python>[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2]</lang>
((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2)
 
# More generally, the list comprehension syntax can be understood as a concise syntactic sugaring
Or as an iterator:
# of a use of the list monad, in which non-matches are returned as empty lists, matches are wrapped
# as single-item lists, and concatenation flattens the output, eliminating the empty lists.
 
# The monadic 'bind' operator for lists is concatMap, traditionally used with its first two arguments flipped.
<lang python>((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2)</lang>
# The following three formulations of a '''pts''' (pythagorean triangles) function are equivalent:
 
from functools import (reduce)
More generally, the list comprehension syntax can be understood as a concise syntactic sugaring of a use of the list monad, in which non-matches are returned as empty lists, matches are wrapped as single-item lists, and concatenation flattens the output, eliminating the empty lists.
 
The monadic 'bind' operator for lists is concatMap, traditionally used with its first two arguments flipped. The following three formulations of a '''pts''' (pythagorean triangles) function are equivalent:
 
<lang python>from functools import (reduce)
from operator import (add)
 
 
# pts :: Int -> [(Int, Int, Int)]
Line 1,968 ⟶ 2,042:
 
 
main()</lang>
</syntaxhighlight>
{{Out}}
<pre>[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
Line 1,976 ⟶ 2,051:
=={{header|R}}==
R has inherent list comprehension:
<syntaxhighlight lang="r">
<lang R>
x = (0:10)
> x^2
Line 1,984 ⟶ 2,059:
> x[x[(0:length(x))] %% 2==0]
[1] 0 2 4 6 8 10
</syntaxhighlight>
</lang>
 
R's "data frame" functions can be used to achieve the same code clarity (at the cost of expanding the entire grid into memory before the filtering step)
 
<syntaxhighlight lang="r">
<lang R>
subset(expand.grid(x=1:n, y=1:n, z=1:n), x^2 + y^2 == z^2)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(for*/list ([x (in-range 1 21)]
Line 2,000 ⟶ 2,075:
#:when (= (+ (* x x) (* y y)) (* z z)))
(list x y z))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Raku has single-dimensional list comprehensions that fall out naturally from nested modifiers; multidimensional comprehensions are also supported via the cross operator; however, Raku does not (yet) support multi-dimensional list comprehensions with dependencies between the lists, so the most straightforward way is currently:
<syntaxhighlight lang="raku" perl6line>my $n = 20;
say gather for 1..$n -> $x {
for $x..$n -> $y {
for $y..$n -> $z {
Line 2,012 ⟶ 2,087:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))</pre>
 
Note that <tt>gather</tt>/<tt>take</tt> is the primitive in Raku corresponding to generators or coroutines in other languages. It is not, however, tied to function call syntax in Raku. We can get away with that because lists are lazy, and the demand for more of the list is implicit; it does not need to be driven by function calls.
 
=={{header|Rascal}}==
<syntaxhighlight lang="rascal">
<lang Rascal>
public list[tuple[int, int, int]] PythTriples(int n) = [<a, b, c> | a <- [1..n], b <- [1..n], c <- [1 .. n], a*a + b*b == c*c];
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 2,026 ⟶ 2,103:
 
===vertical list===
<langsyntaxhighlight lang="rexx">/*REXX program displays a vertical list of Pythagorean triples up to a specified number.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 100 /*Not specified? Then use the default.*/
Line 2,044 ⟶ 2,121:
end /*j*/ /* [↑] list the members vertically. */
say
say # ' members listed.' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre style="height:45ex">
Line 2,105 ⟶ 2,182:
 
===horizontal list===
<langsyntaxhighlight lang="rexx">/*REXX program shows a horizontal list of Pythagorean triples up to a specified number. */
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 100 /*Not specified? Then use the default.*/
Line 2,132 ⟶ 2,209:
end /*j*/
say strip($); say
say # ' members listed.' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the following input: &nbsp; <tt> 35 </tt>}}
<pre>
Line 2,143 ⟶ 2,220:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for x = 1 to 20
for y = x to 20
Line 2,152 ⟶ 2,229:
next
next
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 2,168 ⟶ 2,245:
{{works with|Ruby|1.9.2}}
 
<langsyntaxhighlight lang="ruby">n = 20
# select Pythagorean triplets
Line 2,176 ⟶ 2,253:
[[x, y, z]].keep_if { x * x + y * y == z * z }}}})
 
p r # print the array _r_</langsyntaxhighlight>
 
Output: <tt>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]]</tt>
Line 2,190 ⟶ 2,267:
 
Illustrating a way to avoid all loops (but no list comprehensions) :
<langsyntaxhighlight lang="ruby">n = 20
p (1..n).to_a.combination(3).select{|a,b,c| a*a + b*b == c*c}
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for x = 1 to 20
for y = x to 20
for z = y to 20
Line 2,201 ⟶ 2,278:
next z
next y
next x</langsyntaxhighlight>Output:
<pre>[3,4,5]
[5,12,13]
Line 2,218 ⟶ 2,295:
First using the built-in iterator trait, we can simply flat-map and then filter-map:
 
<langsyntaxhighlight lang="rust">fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> {
(1..=n).flat_map(move |x| {
(x..=n).flat_map(move |y| {
Line 2,230 ⟶ 2,307:
})
})
}</langsyntaxhighlight>
 
* Using <code>flat_map</code> we can map and flatten an iterator.
Line 2,244 ⟶ 2,321:
Using the above and <code>macro_rules!</code> we can implement comprehension with a reasonably sized macro:
 
<langsyntaxhighlight lang="rust">macro_rules! comp {
($e:expr, for $x:pat in $xs:expr $(, if $c:expr)?) => {{
$xs.filter_map(move |$x| if $($c &&)? true { Some($e) } else { None })
Line 2,251 ⟶ 2,328:
$xs.flat_map(move |$x| comp!($e, $(for $y in $ys),+ $(, if $c)?))
}};
}</langsyntaxhighlight>
 
The way to understand a Rust macro is it's a bit like regular expressions. The input matches a type of token, and expands it into the block, for example take the follow pattern:
 
<langsyntaxhighlight lang="rust">($e:expr, for $x:pat in $xs:expr $(, if $c:expr)?)</langsyntaxhighlight>
 
# matches an <code>expr</code> expression, defines it to <code>$e</code>
Line 2,268 ⟶ 2,345:
This makes the two following blocks equivalent:
 
<langsyntaxhighlight lang="rust">comp!(x, for x in 0..10, if x != 5)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">(0..10).filter_map(move |x| {
if x != 5 && true {
Some(x)
Line 2,276 ⟶ 2,353:
None
}
})</langsyntaxhighlight>
 
The most interesting part of <code>comp!</code> is that it's a recursive macro (it expands within itself), and that means it can handle any number of iterators as inputs.
Line 2,284 ⟶ 2,361:
The pythagorean function could as such be defined as the following:
 
<langsyntaxhighlight lang="rust">fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> {
comp!(
[x, y, z],
Line 2,292 ⟶ 2,369:
if x.pow(2) + y.pow(2) == z.pow(2)
)
}</langsyntaxhighlight>
 
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def pythagoranTriangles(n: Int) = for {
x <- 1 to 21
y <- x to 21
z <- y to 21
if x * x + y * y == z * z
} yield (x, y, z)</langsyntaxhighlight>
 
which is a syntactic sugar for:
 
<langsyntaxhighlight lang="scala"> def pythagoranTriangles(n: Int) = (1 to n) flatMap (x =>
(x to n) flatMap (y =>
(y to n) filter (z => x * x + y * y == z * z) map (z =>
(x, y, z))))</langsyntaxhighlight>
 
Alas, the type of collection returned depends on the type of the collection
Line 2,317 ⟶ 2,394:
To get a <code>List</code> out of it, just pass a <code>List</code> to it:
 
<langsyntaxhighlight lang="scala">def pythagoranTriangles(n: Int) = for {
x <- List.range(1, n + 1)
y <- x to 21
z <- y to 21
if x * x + y * y == z * z
} yield (x, y, z)</langsyntaxhighlight>
 
Sample:
Line 2,334 ⟶ 2,411:
Scheme has no native list comprehensions, but SRFI-42 [http://srfi.schemers.org/srfi-42/srfi-42.html] provides them:
 
<langsyntaxhighlight lang="scheme">
(list-ec (:range x 1 21)
(:range y x 21)
Line 2,340 ⟶ 2,417:
(if (= (* z z) (+ (* x x) (* y y))))
(list x y z))
</syntaxhighlight>
</lang>
 
<pre>
Line 2,348 ⟶ 2,425:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">var n = 20
say gather {
for x in (1 .. n) {
Line 2,357 ⟶ 2,434:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,365 ⟶ 2,442:
=={{header|Smalltalk}}==
{{works with|Pharo|1.3-13315}}
<langsyntaxhighlight lang="smalltalk">
| test |
 
Line 2,382 ⟶ 2,459:
#(9 12 15)
#(12 16 20)"
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
Line 2,388 ⟶ 2,465:
Stata does no have list comprehensions, but the Mata matrix language helps simplify this task.
 
<langsyntaxhighlight lang="stata">function grid(n,p) {
return(colshape(J(1,p,1::n),1),J(n,1,1::p))
}
Line 2,395 ⟶ 2,472:
a = grid(n,n)
a = a,sqrt(a[.,1]:^2+a[.,2]:^2)
a[selectindex(floor(a[.,3]):==a[.,3] :& a[.,3]:<=n),]</langsyntaxhighlight>
 
'''Output'''
Line 2,416 ⟶ 2,493:
 
=={{header|SuperCollider}}==
<langsyntaxhighlight lang="supercollider">
var pyth = { |n|
all {: [x,y,z],
Line 2,426 ⟶ 2,503:
};
 
pyth.(20) // example call</langsyntaxhighlight>
returns
<langsyntaxhighlight lang="supercollider">[ [ 3, 4, 5 ], [ 5, 12, 13 ], [ 6, 8, 10 ], [ 8, 15, 17 ], [ 9, 12, 15 ], [ 12, 16, 20 ] ]</langsyntaxhighlight>
 
=={{header|Swift}}==
{{incorrect|Swift|They should be distinct from (nested) for loops and the use of map and filter functions within the syntax of the language.}}
 
<langsyntaxhighlight lang="swift">typealias F1 = (Int) -> [(Int, Int, Int)]
typealias F2 = (Int) -> Bool
 
Line 2,446 ⟶ 2,523:
}
 
print(pythagoreanTriples(n: 20))</langsyntaxhighlight>
 
{{out}}
Line 2,454 ⟶ 2,531:
=={{header|Tcl}}==
Tcl does not have list comprehensions built-in to the language, but they can be constructed.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# from http://wiki.tcl.tk/12574
Line 2,498 ⟶ 2,575:
 
set range {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20}
puts [lcomp {$x $y $z} x $range y $range z $range {$x < $y && $x**2 + $y**2 == $z**2}]</langsyntaxhighlight>
<pre>{3 4 5} {5 12 13} {6 8 10} {8 15 17} {9 12 15} {12 16 20}</pre>
 
Line 2,505 ⟶ 2,582:
TI-89 BASIC does not have a true list comprehension, but it has the seq() operator which can be used for some similar purposes.
 
<langsyntaxhighlight lang="ti89b">{1, 2, 3, 4} → a
seq(a[i]^2, i, 1, dim(a))</langsyntaxhighlight>
 
produces {1, 4, 9, 16}. When the input is simply a numeric range, an input list is not needed; this produces the same result:
 
<langsyntaxhighlight lang="ti89b">seq(x^2, x, 1, 4)</langsyntaxhighlight>
 
=={{header|Transd}}==
The language's construct for list comprehension closely follows the established set-builder notation:
 
<pre>
FOR x IN <SET>
WHERE predicate(x)
PROJECT f(x)
</pre>
The special form of 'for' construct performs list comprehension and returns a collection with selected elements.
 
In basic form, the returned vector is created and filled automatically:
 
<syntaxhighlight lang="Scheme">
(with v (for x in Range(10)
project (* x x))
(textout v))
</syntaxhighlight>
{{out}}
<pre>
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</pre>
 
Basic form with 'WHERE' clause:
 
<syntaxhighlight lang="Scheme">
(with v (for x in Range(10)
where (mod x 2)
project Vector<ULong>([x,(* x x)]))
(textout v))
</syntaxhighlight>
{{out}}
<pre>
[[1, 1], [3, 9], [5, 25], [7, 49], [9, 81]]
</pre>
 
In cases when more customized behaviour is required, there is an option to define
and fill the returned collection directly:
 
<syntaxhighlight lang="Scheme">
(with v (for x in Range(1 n) project<Vector<ULong>>
(for y in Range(x n) do
(for z in Range(y n)
where (== (* z z) (+ (* y y) (* x x)))
do (append @projRes Vector<ULong>([x,y,z])))))
(textout "Pythagorean triples:\n" v))
}</syntaxhighlight>
{{out}}
<pre>
Pythagorean triples:
[[3, 4, 5], [5, 12, 13], [6, 8, 10], [9, 12, 15]]
</pre>
 
=={{header|Visual Basic .NET}}==
Line 2,516 ⟶ 2,645:
{{trans|C#}}
 
<langsyntaxhighlight lang="vbnet">Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
Line 2,528 ⟶ 2,657:
Next
End Sub
End Module</langsyntaxhighlight>
 
Output:
Line 2,544 ⟶ 2,673:
VP7 has explicit list comprehension syntax.
 
<syntaxhighlight lang="visualprolog">
<lang visualProlog>
implement main
open core, std
Line 2,571 ⟶ 2,700:
goal
mainExe::run(main::run).
</syntaxhighlight>
</lang>
 
=={{header|Wrapl}}==
<langsyntaxhighlight lang="wrapl">ALL WITH x <- 1:to(n), y <- x:to(n), z <- y:to(n) DO (x^2 + y^2 = z^2) & [x, y, z];</langsyntaxhighlight>
 
=={{header|Wren}}==
Using a generator.
<langsyntaxhighlight ecmascriptlang="wren">var pythTriples = Fiber.new { |n|
(1..n-2).each { |x|
(x+1..n-1).each { |y|
Line 2,590 ⟶ 2,719:
var res = pythTriples.call(n)
res && System.print(res)
}</langsyntaxhighlight>
 
{{out}}
Line 2,603 ⟶ 2,732:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var n=20;
[[(x,y,z); [1..n]; {[x..n]}; {[y..n]},{ x*x + y*y == z*z }; _]]
//-->L(L(3,4,5),L(5,12,13),L(6,8,10),L(8,15,17),L(9,12,15),L(12,16,20))</langsyntaxhighlight>
Lazy:
<langsyntaxhighlight lang="zkl">var n=20;
lp:=[& (x,y,z); // three variables, [& means lazy/iterator
[1..n]; // x: a range
Line 2,617 ⟶ 2,746:
// with values x,y,z, or just _ (which means return arglist)
]];
lp.walk(2) //-->L(L(3,4,5),L(5,12,13))</langsyntaxhighlight>
 
 
9,476

edits