Jump to content

List comprehensions: Difference between revisions

m
Fixed lang tags (using MediaWiki::API).
No edit summary
m (Fixed lang tags (using MediaWiki::API).)
Line 22:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algolalgol68>MODE XYZ = STRUCT(INT x,y,z);
 
OP +:= = (REF FLEX[]XYZ lhs, XYZ rhs)FLEX[]XYZ: (
Line 43:
 
=={{header|C++}}==
<lang C++cpp>#include <vector>
#include <vector>
#include <cmath>
#include <iostream>
Line 76 ⟶ 75:
}
This produces the following output:
3 4 5 5 12 13 6 8 10 8 15 17 9 12 15 12 16 20</lang>
</lang>
 
=={{header|Clojure}}==
<lang lisp>(for [x (range 1 21) y (range x 21) z (range y 21) :when (= (+ (* x x) (* y y)) (* z z))] [x y z])</lang>
 
=={{header|Common Lisp}}==
Line 112 ⟶ 110:
=={{header|E}}==
 
<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]) } } } }</lang>
 
=={{header|Erlang}}==
 
<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 ].</lang>
 
=={{header|Haskell}}==
Line 140 ⟶ 138:
 
=={{header|J}}==
<lang J>(#~ (2&{ = 1&{ +&.:*: 0&{)@|:)@(1+3&# #: i.@^&3)</lang>
 
The idiom here has two major elements:
Line 179 ⟶ 177:
 
=={{header|Mathematica}}==
<nowikilang mathematica>Select[Tuples[Range[n], 3], #1[[1]]^2 + #1[[2]]^2 == #1[[3]]^2 &]</nowikilang>
 
=={{header|OCaml}}==
Line 218 ⟶ 216:
List comprehension:
 
<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 comprehension (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>
 
=={{header|Ruby}}==
Line 285 ⟶ 283:
TI-89 BASIC does not have a true list comprehension, but it has the seq() operator which can be used for some similar purposes.
 
<lang ti89b>{1, 2, 3, 4} → a
seq(a[i]^2, i, 1, dim(a))</lang>
 
produces {1, 4, 9, 16}. When the input is simply a numeric range, an input list is not needed; this produces the same result:
 
<lang ti89b>seq(x^2, x, 1, 4)</lang>
845

edits

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