Neon
← Back to ListsNext: Calling functions →

Containers

Containers are custom data structures that group named fields (like objects in other languages). Each container has a type name (e.g., Person, Point).


1. Defining and Using Containers

Syntax

containerVariable = ContainerType(field1: value1, field2: value2, ...)

Rules

Example

# Define a Person container
alice = Person(firstName: "Alice", lastName: "Smith", age: 30)

# Define another Person (must have the same fields)
bob = Person(lastName: "Johnson", firstName: "Bob", age: 25)

# Access fields with >>
print(alice>>firstName)  # → "Alice"
print(bob>>age)          # → 25

# Modify fields
alice>>age = 31
print(alice>>age)  # → 31

2. Container Operations

Operation Example Description
Access field person>>name Gets the value of name.
Modify field person>>name = "New Name" Updates the field.
Deep copy copy(person) Creates an independent copy.

Example: Nested Containers

# Define an Address container
home = Address(street: "123 Main St", city: "Paris")

# Define a Person with an Address
alice = Person(name: "Alice", address: home)

# Access nested fields
print(alice>>address>>city)  # → "Paris"

# Modify nested fields
alice>>address>>city = "Berlin"
print(alice>>address>>city)  # → "Berlin"

3. Container Self-Reference

Containers can contain themselves (useful for linked structures like trees).

Example: Linked List Node

# Define a Node container
node1 = Node(value: 1, next: None)
node2 = Node(value: 2, next: node1)  # node2 points to node1
node3 = Node(value: 3, next: node2)  # node3 -> node2 -> node1

# Traverse the list
current = node3
while (current != None) do
    print(current>>value)
    current = current>>next
end
# Output: 3, 2, 1

4. Operator Overloading for Containers

You can override operators for custom container types by defining special methods.

Overloadable Operators

Operator Method Name Example
+ add MyType~add(a, b)
- sub MyType~sub(a, b)
* mul MyType~mul(a, b)
/ div MyType~div(a, b)
% mod MyType~mod(a, b)
// eucl MyType~eucl(a, b)
** pow MyType~pow(a, b)
- (unary) minus MyType~minus(a)
in in MyType~in(a, b)
str() str MyType~str(a)
print() repr MyType~repr(a)

Example: Vector Container with + Overload

# Define a Vector container
v1 = Vector(x: 1, y: 2)
v2 = Vector(x: 3, y: 4)

# Overload the + operator
function Vector~add(a, b) do
    return (Vector(x: a>>x + b>>x, y: a>>y + b>>y))
end

# Now + works on Vectors
v3 = v1 + v2
print(v3>>x)  # → 4
print(v3>>y)  # → 6

Example: Custom String Representation

function Person~repr(p) do
    return ("Person(" + p>>firstName + " " + p>>lastName + ")")
end

alice = Person(firstName: "Alice", lastName: "Smith")
print(alice)  # → "Person(Alice Smith)"

← Back to ListsNext: Calling functions →