Search code examples
pythonlist-comprehensionnim-lang

Nim equivalent of Python's list comprehension


Since Nim shares a lot of features with Python, i would not be surprised if it implements Python's list comprehension too:

string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2', '3', '4', '5']

Is this actually possible in Nim? If not, could be implemented with templates/macros ?


Solution

  • UPDATE: List comprehension has been deprecated since version 0.19.9 (Source). A good alternative is to use the new sugar.collect macro.

    Another update: As of 2023, list comprehension has been removed.


    Outdated original answer

    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.