List comprehensions: Difference between revisions

Added Scala
(Added Oz example.)
(Added Scala)
Line 319:
# no temp array, but a lot of housework to flatten and remove nils
(1..n).collect {|x| (1..n).collect {|y| (1..n).collect {|z| [x,y,z] if x**2 + y**2 == z**2}}}.reduce(:+).reduce(:+).compact</lang></div>
 
=={{header|Scala}}==
<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)</lang>
 
which is a syntactic sugar for:
 
<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))))</lang>
 
Alas, the type of collection returned depends on the type of the collection
being comprehended. In the example above, we are comprehending a <code>Range</code>.
Since a <code>Range</code> of triangles doesn't make sense, it returns the
closest (supertype) collection for which it does, an <code>IndexedSeq</code>.
 
To get a <code>List</code> out of it, just pass a <code>List</code> to it:
 
<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)</lang>
 
Sample:
 
<pre>
scala> pythagoranTriangles(21)
res36: List[(Int, Int, Int)] = List((3,4,5), (5,12,13), (6,8,10), (8,15,17), (9,12,15), (12,16,20))
</pre>
 
=={{header|Tcl}}==
Anonymous user