I'm learning Python. I recently learned about Nim and began to study it too. I liked the python+pascal syntax and the speed of C. Unfortunately, there is much less educational information and reference books about Nim than there is about Python. I don't quite understand how to properly perform a reverse iteration in Nim.
In Python, it's easy. For example, for a "for" loop, the var[::-1] method works easily. And it seems that in Nim it just doesn't work that way. Something like var[^1..0] just give me an error. I was able to do reverse iteration using len() and the "ind" variable that simply gets smaller with each loop.
Here is a code example.
const str: string = "Hello world!"
var str_2: string
var ind: int = len(str)
for i in str:
ind.inc(-1)
str_2.add(str[ind])
echo str_2
It's work. But this is not a pythonic solution. An unnecessary bicycle. In a good way, there should be built-in tools for reverse iteration. Nim experts, what are the main methods of reverse iteration?
Sorry for my English. I write with the help of an online translator.
I tried using a reverse iteration like var[^1..0]. It just gives an error. I also tried to use the "countdown" function, but that's not what it's needed for. I would like to learn about the main and right methods of reverse iteration in Nim.
I don't know what's wrong with
countdown. For example, you can use it to iterate froma.len - 1down to0(much like Pascal'sfor r := length(a) - 1 downto 0 do), andaddthe characters at those positions, thus in reverse order, to a new string:But to just reverse a string, you could also go using an openArray and
reversedfromstd/algorithm, thencastit back to a string:Or, as @xbello has pointed out in this comment, use the same procedure from
std/unicode, which directly (accepts and) returns string types, eliminating the need tocastmanually.All of the above produce: