Lists
Lists in Zard are dynamic containers capable of holding multiple elements of the same type. They support addition, removal, access, and clearing operations, all type-safe and efficient.
Declaring Lists
If a list is created empty, the type must be declared explicitly:
List<int> numbers;
If initialized with values, the compiler infers the type automatically from the first element, eliminating the need to inform <type>:
List nomes = ("zard", "angel");
Mixing incompatible types will cause a compile-time error:
# ❌ Invalid example — inferred as <double>, but second element is <string>
List test = (3.14, "hello");
Adding Elements
Use add() to insert a single element, and addAll() to add multiple at once:
numbers.add(3);
int x = 2;
numbers.addAll(3, 4, 5, x);
Getting the Size
The size() method returns the total number of elements.
It must be called within an expression or assignment.
int z = numbers.size();
print(z);
print(numbers.size());
Removing Elements
Remove an element by its index using remove(index):
numbers.remove(0);
Accessing Elements
Use get(index) to retrieve an element by its position:
print(numbers.get(1));
Clearing a List
The clear() method removes all elements from the list:
numbers.clear();
Restrictions: No Lists of Lists
In Zard, it is not allowed to have a list that holds other lists or use List<List<T>>.
This design decision ensures clarity and avoids potential performance issues in the ARC memory system..
# ❌ Invalid example — Lists cannot contain other lists.
List<List<int>> matrix;
To model more complex structures like matrices or tables, use structs instead:
struct Matrix {
List<int> row;
}
List<Matrix> matrix;
Full Example
main {
# If instantiated empty, type must be declared
List<int> numbers;
# If initialized with values, type is inferred
List nomes = ("zard", "angel");
# Adding values
numbers.add(3);
int x = 2;
numbers.addAll(3,4,5,x);
# Getting size
int z = numbers.size();
print(z);
print(numbers.size());
# Removing
numbers.remove(0);
# Accessing
print(numbers.get(1));
# Clearing
numbers.clear();
}