Want to create a list (a resizable array of items) in Nim? You can do this with 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"]
To iterate over the list:
var fruits = @["apple", "banana"]
for fruit in fruits:
echo fruit
Running this yields:
apple
banana
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
An item can be deleted from the sequence:
var fruits = @["apple", "banana", "cherry"]
fruits.delete(1)
echo fruits
Running this yields:
@["apple", "cherry"]
Leave a comment