Jump to content

List comprehensions: Difference between revisions

→‎{{header|Nim}}: Add example using collect()
(Added 11l)
(→‎{{header|Nim}}: Add example using collect())
Line 1,565:
 
=={{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>
 
ThereA arespecial nosyntax for list comprehensions in Nim, butcan be implemented thanks to the strong metaprogramming capabilities we can implement our own:
<lang nim>import macros
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.