How to use a list in Nim

Want to create a list (a resizable array of items) in Nim? You can do this with a sequence.

Creating a sequence

A sequence can be created, and added to:

var fruits = newSeq[string]()
fruits.add("apple")
fruits.add("banana")

echo fruits

or can be initialized with elements:

var fruits = @["apple", "banana"]
echo fruits

The output of the above samples is the same:

@["apple", "banana"]

Iterating over a sequence

To iterate over the list:

var fruits = @["apple", "banana"]
for fruit in fruits:
  echo fruit

Running this yields:

apple
banana

Testing existence of a value in the sequence

To test if the value exists in the list:

var fruits = @["apple", "banana"]
let appleExists = "apple" in fruits
echo appleExists

The contains method can also be used:

var fruits = @["apple", "banana"]
let appleExists = fruits.contains("apple")
echo appleExists

Running either of the above samples yields:

true

Deleting an entry from the list

An item can be deleted from the sequence:

var fruits = @["apple", "banana", "cherry"]
fruits.delete(1)
echo fruits

Running this yields:

@["apple", "cherry"]

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.