List comprehensions: Difference between revisions

Content added Content deleted
(Added 11l)
(→‎{{header|Nim}}: Add example using collect())
Line 1,565: Line 1,565:


=={{header|Nim}}==
=={{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 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</lang>
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:
<lang nim>import macros
<lang nim>import macros