Nim equivalent of Python's list comprehension
UPDATE: List comprehension has been deprecated since version 0.19.9 (Source).
List comprehension is implemented in Nim in the sugar
package (i.e., you have to import sugar
). It is implemented as a macro called lc
and allows to write list comprehensions like this:
lc[x | (x <- 1..10, x mod 2 == 0), int]
lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]
Note that the macro requires to specify the type of the elements.
According to rosettacode, Nim has no list comprehensions, but they can be created through metaprogramming.
[EDIT]
As pointed out by bluenote10, list comprehensions are now part of the future module:
import future
var str = "Hello 12345 World"
echo lc[x | (x <- str, ord(x) - ord('0') in 0..9), char]
The above snippet yields @[1, 2, 3, 4, 5]
import sugar
let items = collect(newSeq):
for x in @[1, 2, 3]: x * 2
echo items
outputs @[2, 4, 6]