iteratoriterationnim-lang

What are the main ways to do a reverse iteration in Nim?


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.


Solution

  • I also tried to use the "countdown" function, but that's not what it's needed for.

    I don't know what's wrong with countdown. For example, you can use it to iterate from a.len - 1 down to 0 (much like Pascal's for r := length(a) - 1 downto 0 do), and add the characters at those positions, thus in reverse order, to a new string:

    const a: string = "Hello world!"
    
    var b: string
    for r in countdown(a.len - 1, 0): b.add a[r]
    echo b
    

    But to just reverse a string, you could also go using an openArray and reversed from std/algorithm, then cast it back to a string:

    import std/algorithm
    
    const a: string = "Hello world!"
    echo cast[string](a.reversed)
    

    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 to cast manually.

    import std/unicode
    
    const a: string = "Hello world!"
    echo a.reversed
    

    All of the above produce:

    !dlrow olleH