Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 915
Arrrrrrr Avatar asked Apr 27 '15 12:04

Arrrrrrr


People also ask

What is comprehension equivalent in Python?

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.

Does Python have list comprehension?

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.

Is list comprehension faster than Numpy?

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.

What languages have list comprehensions?

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.


1 Answers

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.

like image 164
bluenote10 Avatar answered Sep 18 '22 16:09

bluenote10