Skip to content
Plumlang

Language reference · Section 8

Trees: classes and objectsStage 5

8.1 Declaring a tree

A tree groups fields and the methods that work on them:

tree Account {
    owner: str
    balance: float = 0.0

    branch deposit(amount: float) {
        if amount <= 0 {
            throw ValueError("deposit must be positive")
        }
        self.balance += amount
    }

    branch to_str() -> str => "{self.owner}: {self.balance:.2}"
}

plant acct = Account("Ada")          # balance takes its default
acct.deposit(50)
drop(acct)                           # Ada: 50.00

Inside a method, self is the object; fields and methods are always reached through it (self.balance), so a field is never confused with a local variable.

8.2 Construction

Calling the tree's name creates an object. By default the arguments fill the fields in declaration order; fields with defaults may be left out or named: Account("Ada", balance: 10.0).

A tree may define init to construct objects differently. When it does, calls to the tree's name call init. Fields with defaults are set first; init must then set every field without a default, in its opening statements (self.field = value), before anything else uses self. A tree that inherits init and adds a field without a default needs its own init.

tree Temperature {
    celsius: float

    branch init(fahrenheit: float) {
        self.celsius = (fahrenheit - 32.0) * 5.0 / 9.0
    }
}

8.3 Objects are shared

Tree objects are reference values: assigning or passing one shares the same object, and changes through one name are seen through every name. Every other value in Plumlang is copied (section 11). For a tree without equals, a == b asks whether two names refer to the same object (section 4.5).

8.4 Inheritance

A tree can extend one other tree. It inherits the fields and methods, adds its own, and can override methods. super.method() calls the parent's version.

tree Animal {
    name: str
    branch speak() -> str => "..."
}

tree Dog : Animal {
    branch speak() -> str => "{self.name} says woof"
}

plant pets: list[Animal] = [Dog("Rex"), Animal("Generic")]
for pet in pets { drop(pet.speak()) }

A Dog can be used wherever an Animal is expected. There is no multiple inheritance; use traits.

8.5 Traits

A trait lists methods a tree promises to have. A tree implements traits by naming them after :, after its parent tree if it has one:

trait Shape {
    branch area() -> float
    branch name() -> str => "shape"     # a default method
}

tree Circle : Shape {
    radius: float
    branch area() -> float => 3.14159 * self.radius ** 2
}

branch total_area(shapes: list[Shape]) -> float {
    plant sum = 0.0
    for s in shapes { sum += s.area() }
    return sum
}

Missing methods are compile errors, and a tree's version of a trait's method (or of a parent's method it overrides) must have exactly the same parameters and result. x is Shape asks whether an object's tree has the trait.

Some methods the language calls itself:

  • to_str() -> str is how an object prints: in drop, str() and interpolation, and inside a printed list or map. Without it, an object prints as <TreeName>.

  • equals(other: T) -> bool, where T is the tree or one it extends, is what a == b and a != b mean when a's type is a tree with equals (trait Equal). Without it, == asks whether both are the same object. In a list whose item type has equals (also lists of such lists), contains, index_of, x in list and == between lists use it too, calling each item's equals. Elsewhere in collections (map keys and values, sets, a list of a parent tree whose subclass alone has equals) objects compare by identity.

  • compare(other: T) -> int (trait Order) is what a < b, a <= b, a > b and a >= b mean: it returns a negative number if self comes before other, zero if neither does, and a positive number if self comes after. A list whose item type has compare can sort() and sorted(); the sort is stable. A compare that throws stops the sort with its error.

  • The arithmetic operators call these methods (on the left object):

    Operator Method
    a + b plus(other: T) -> T
    a - b minus(other: T) -> T
    a * b times(other: T) -> T, or times(k: int) / times(k: float)
    a / b divided_by(other: T) -> T, or divided_by(k: int) / divided_by(k: float)
    -a negate() -> T

    T is the tree or one it extends (or a trait it has), and the result is too; times and divided_by may take a number instead, to scale. Compound assignment uses them as well: v += w is v = v + w. The object must be on the left: v * 2.0 works, 2.0 * v doesn't.

tree Vector {
    x: float
    y: float
    branch plus(other: Vector) -> Vector => Vector(self.x + other.x, self.y + other.y)
    branch times(k: float) -> Vector => Vector(self.x * k, self.y * k)
    branch negate() -> Vector => Vector(-self.x, -self.y)
}

plant v = Vector(1.0, 2.0) + Vector(3.0, 4.0) * 2.0    # (7.0, 10.0)
v += -v                                                # (0.0, 0.0)

These methods are found in the object's own tree, so a subclass that overrides one changes what the operator does, even where the object's type is the parent. Their shapes are fixed (E0424), and an override has the same parameters and result as the method it overrides (E0421).

Hash (hash, for map keys) and Iterable (iter, for for) come with the standard library.

Fields and methods whose names start with _ are private to the tree and the trees that extend it (section 9.4).

8.6 Kinds: enumerations

A kind is a type with a fixed set of cases. Cases may carry values.

kind Direction { North, East, South, West }

kind Shape {
    Circle(radius: float)
    Rect(width: float, height: float)
}

branch area(s: Shape) -> float => match s {
    Circle(r) => 3.14159 * r ** 2
    Rect(w, h) => w * h
}

plant heading = Direction.North

match on a kind must cover every case.

A kind's values are values like numbers and strings: two are equal when they are the same case with equal contents (Shape.Rect(2.0, 3.0) == Shape.Rect(2.0, 3.0)), and they print as written: Direction.North, Shape.Circle(1.0). type_of gives the kind's name.