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 ?
We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence.
Python is famous for allowing you to write code that's elegant, easy to write, and almost as easy to read as plain English. One of the language's most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code.
List comprehensions on tiny lists are faster than doing the same with numpy as the performance gain from using numpy is not enough to offset the overhead of creating an array.
List comprehensions are used in a variety of languages. They are most often found in functional languages like Haskell and Scala and in scripting languages like Python and Perl. They are typically faster than other methods of building lists, such as for loops.
UPDATE: List comprehension has been deprecated since version 0.19.9 (Source). A good alternative is to use the new sugar.collect macro.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With