I love Python - especially since I discovered the book “Fluent Python” by Luciano Ramalho. Python is a great programming language when you understand how it works, and some useful tricks like list comprehensions. Nim inherited the syntax of Python and the performance of C.
One of the first thing I do with Nim is to build lists like Python, and I remember a lot of posts in the Internet of Nim users that don’t understand how to use list comprehensions with this programming language. However, list comprehensions in Nim has basically the same implementation as Python… This post is to give some examples of how to use list comprehensions in Nim, and make the parallel with Python to show you that it’s just a “syntax thing”.
To use list comprehensions in Nim, you have to import the module “future”. This module contains some experimental features, which may soon be moved to core modules (Nim isn’t stable for now). This is the syntax of the list comprehension macro:
A macro, in Nim, is a compile-time code transformation. So, instead of code some boring and excessive stuff to build a simple list, you just can use a flexible syntax for this. This macro takes as parameters an expression to build the list, and the type of elements in the list. For example, you can use this example to build a simple list of integers between 0 and 100:
In Python, you can program this thing using:
Ok, this example was not relevant and useful, because you can just build a generator of integers between 0 and 100 and not store all those data in a list… Let’s try an other thing!
Here, you have two arrays of integers:
snd_integers, and you just want to multiply each integer of the first array with each element of the second array. It’s really simple with Nim:
This solution outputs the expected result:
@[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 60, 62, 64, ..., 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400]. Now, we want to multiply each element which is a multiple of 2, from
fst_integers and from
snd_integers! To do that, we just have to add a simple condition at our expression to get all multiple of 2:
In the previous example, we selected interesting integers to resolve our problem: all multiple of 2. To select a multiple of 2, we just have to know if this integer is divisible with 2! :-) We can also program the same list with:
Now, what if I gave you this piece of code and asked you the solution:
? This morning, a programer told me: “Easy, it’s the same integer each time: (0,0,0), (1,1,1), (2,2,2), …”. NO! This code is similar to the previous one (using 2 lists). In Python, this is the implementation of the last list building:
and this code returns to you the set of each tuple existing from these initialized values! The conclusion? List comprehensions in Nim is similar to Python, and the difference is just a “syntax thing”…