Search code examples
sequencenim-lang

Why isn't the order of a sequence kept in nim when deleting an element?


I am trying out nim and struggling with a strange behaviour while working with sequences.

If i run this code:

var
    hobbies = @["Coding", "Creating", "Sports"]

echo hobbies

hobbies.add("Nature")
echo hobbies

hobbies.del(0)
echo hobbies

I would expect this output, because I thought its working like a queue:

@["Coding", "Creating", "Sports"]
@["Coding", "Creating", "Sports", "Nature"]
@["Creating", "Sports", "Nature"]

but insted i get this:

@["Coding", "Creating", "Sports"]
@["Coding", "Creating", "Sports", "Nature"]
@["Nature", "Creating", "Sports"]

After deleting via index .del(0) The value "Nature" is switching to index 0.

Shouldn't the order be kept?

Version:

Nim Compiler Version 1.6.14 [Linux: amd64]
Compiled at 2023-06-29

Solution

  • del operation swaps the last items with the item being removed and then pops it. Has constant complexity.

    If you want to preserve order of elements then you'll need to use delete operation that will shift index of each item after the item being removed by 1. This operation has linear complexity proportional to the size of the sequence.