Skip to main content

Classes

Sometimes one name should mean different code for different types: turning a number into text isn't the same as turning a list into text. Bolt does this with classes, which work like Haskell's type classes and Rust's traits.

Classes aren't compiled yet

bolt run runs everything on this page, but bolt run --wasm and bolt build can't compile calls of class methods yet (#182).

Defining a class​

A class names some functions that a type can provide:

class Describe[T] {
fn describe(x: T) -> String;
}

T stands for the type that the class is for. This says: a type T is describable if there's a function describe that takes a T and gives a String.

Impls​

An impl provides the functions of a class for one type:

class Describe[T] {
fn describe(x: T) -> String;
}

struct Dog { name: String }

impl Describe[Dog] {
fn describe(d) = "a dog called " <> d.name;
}

impl Describe[Bool] {
fn describe(b) = if b { "yes" } else { "no" };
}

describe(Dog { name: "Rex" });
describe(True);

The methods of an impl don't need types: they come from the class. Here d is a Dog and b is a Bool.

Calling describe on a type without an impl is an error:

class Describe[T] {
fn describe(x: T) -> String;
}

impl Describe[Bool] {
fn describe(b) = if b { "yes" } else { "no" };
}

describe(42);
[E0203] Error: there is no instance `Describe[i32]`

Using classes in generic functions​

A function that calls a class method on a value of unknown type only works for types that have an impl. Bolt infers that too:

class Describe[T] {
fn describe(x: T) -> String;
}

fn shout(x) = describe(x) <> "!";

shout gets the type

forall a. Describe[a] => fn(a) -> String

The part before => is a constraint: shout works for any type a that has an impl of Describe.

With written type parameters, write the constraint after the parameter, or in a where clause:

class Describe[T] {
fn describe(x: T) -> String;
}

fn shout[T: Describe](x: T) -> String = describe(x) <> "!";

fn both[A, B](a: A, b: B) -> String where Describe[A], Describe[B] =
describe(a) <> " and " <> describe(b);

A struct or enum can have constraints on its type parameters too. They're checked wherever a value is made:

class Describe[T] {
fn describe(x: T) -> String;
}

impl Describe[i32] {
fn describe(n) = "a number";
}

struct Labeled[T: Describe] { value: T }

let a = Labeled { value: 1 }; // fine
let b = Labeled { value: True }; // error: there is no instance `Describe[Bool]`

The error points at the Describe of Labeled too, since that's what asks for it. A function or impl that uses a Labeled[T] still has to say T: Describe itself if it needs it.

Generic impls​

An impl can have type parameters too, and constraints on them. This one describes any Option whose content can be described:

class Describe[T] {
fn describe(x: T) -> String;
}

impl Describe[i32] {
fn describe(n) = "a number";
}

impl[T] Describe[Option[T]] where Describe[T] {
fn describe(o) = match o {
Some(x) => "some " <> describe(x),
None => "nothing",
};
}

describe(Some(Some(5)));

To check describe(Some(Some(5))), Bolt needs Describe[Option[Option[i32]]]. The generic impl provides it if there's Describe[Option[i32]], which it provides if there's Describe[i32], which there is.

Superclasses​

A class can require another one. Every type that's Ord must also be Eq, the prelude's class of types whose values can be compared with eq:

class Ord[T] where Eq[T] {
fn lt(a: T, b: T) -> Bool;
}

fn less_or_equal[T: Ord](a: T, b: T) -> Bool = lt(a, b) || eq(a, b);

less_or_equal only asks for Ord, but it can use eq as well, since Ord implies Eq.

Constants in classes​

A class can have constants as well as functions:

class Zero[T] {
const ZERO: T;
}

impl Zero[i32] {
const ZERO: i32 = 0;
}

impl Zero[f64] {
const ZERO: f64 = 0.0;
}

let a: i32 = ZERO;
let b: f64 = ZERO;

Which ZERO is meant depends on the type that's expected.

Associated types​

A class can also declare a type that each impl chooses. A class of containers that can be indexed doesn't know what they contain, so it names the type of their elements Item, and each impl says what it is:

class Index[C] {
type Item;
fn at(c: C, i: i32) -> Item;
}

struct Stack[T] { items: [T] }

impl[T] Index[Stack[T]] {
type Item = T;
fn at(s, i) = s.items[i];
}

let s = Stack { items: [True, False] };
let top: Bool = at(s, 0);

Inside the class, Item stands for the type of the impl that's used. Here it's Bool, since s is a Stack[Bool].

A function with a type parameter can name it as C.Item, if a bound or a where clause says which class it comes from:

fn first[C](c: C) -> C.Item where Index[C] = at(c, 0);

Without written types, Bolt finds it by itself: fn first(c) = at(c, 0); has the type forall a. Index[a] => fn(a) -> a.Item.

A bound or where clause can also say what an associated type is, with Item = ... after the class's other arguments. Then the function can count on it:

fn sum[C: Index[Item = i32]](c: C) -> i32 = at(c, 0) + at(c, 1);

sum(Stack { items: [1, 2] });
3

A call checks it: sum(Stack { items: [True, False] }) is an error, since there Item is Bool, not i32. The same works in a where clause, as where Index[C, Item = i32] or where C: Index[Item = i32].

An associated type can have a bound, which every impl's type for it must meet. In return, code that knows a type has an instance of the class can count on it. The prelude's Iterable says that what iter gives is an Iterator:

class Iterable[C] {
type Iter: Iterator;
fn iter(c: C) -> Iter;
}

So a function that only asks for Iterable can loop, and use what the iterator gives, like C.Iter.Item:

fn count[C: Iterable](c: C) -> i32 {
let mut n = 0;
for x in c {
n += 1;
}
n
}

count(Vec.from_array([1, 2, 3]));
3

Classes with several parameters​

A class can relate several types:

class Convert[A, B] {
fn convert(a: A) -> B;
}

impl Convert[i32, String] {
fn convert(n) = "a number";
}

let s: String = convert(42);

Classes that syntax uses​

The prelude defines four classes that Bolt's own syntax uses, so that a type of your own can be indexed and looped over like an array:

SyntaxClassMethod
c[i]Index[C], with type Itemfn index(c: C, i: i32) -> Item
c[i] = xIndexMut[C]fn set_index(c: C, i: i32, x: C.Item)
for x in cIterable[C], with type Iterfn iter(c: C) -> Iter
Iterator[I], with type Itemfn next(it: I) -> Option[Item]

for x in c calls iter(c) once, then next on the iterator until it gives None. c[i] += x calls index and then set_index. Arrays use them too: the prelude has impls for arrays, and so does Vec:

struct Ring { items: [i32] }

impl Index[Ring] {
type Item = i32;
fn index(r, i) = r.items[i % array_len(r.items)];
}

let r = Ring { items: [1, 2, 3] };
r[4];
2

FnIter is an iterator made from a function that gives the next item each time it's called, which is the quickest way to make a type Iterable:

struct Countdown { from: i32 }

impl Iterable[Countdown] {
type Iter = FnIter[i32];
fn iter(c) {
let mut n = c.from;
FnIter { next: || if n > 0 { n -= 1; Some(n + 1) } else { None } }
}
}

let mut total = 0;
let countdown = Countdown { from: 3 };
for n in countdown {
total += n;
}
total;
6

A function that indexes or loops over something whose type it doesn't know works for any type with the impls: fn first(c) = c[0]; has the type forall a. Index[a] => fn(a) -> a.Item, and takes arrays and Vecs alike.

Classes of operators​

The prelude also has a class for each operator, like Rust's std::ops:

OperatorClassMethod
a + b, a - b, a * b, a / b, a % bAdd, Sub, Mul, Div, Remfn add(a: T, b: T) -> Output, …
a & b, a | b, a ^ bBitAnd, BitOr, BitXorfn bitand(a: T, b: T) -> Output, …
a << n, a >> nShl, Shrfn shl(a: T, n: u32) -> Output, …
-a, !aNeg, Notfn neg(a: T) -> Output, fn not(a: T) -> Output
a == b, a != bEqfn eq(a: ro T, b: ro T) -> Bool, fn ne(a: ro T, b: ro T) -> Bool
a < b, a > b, a <= b, a >= bPartialOrdfn partial_cmp(a: ro T, b: ro T) -> Option[Ordering], and fn lt(a: ro T, b: ro T) -> Bool, …

Comparing two values doesn't change them, so Eq and PartialOrd take ro T, as do Show and Debug. So an impl for a type works for that type seen as ro too: a function that's given T: Eq can compare what a ro value holds.

Each has an associated type Output, the type of the result, which is T unless an impl says otherwise, and each operator is defined as a function of its method, like fn a + b = add(a, b);. A generic function asks for the operator it needs, and works for any type with an impl:

fn twice[T: Add](x: T) -> T.Output = add(x, x);

struct Money { cents: i32 }

impl Add[Money] {
type Output = Money;
fn add(a, b) = Money { cents: a.cents + b.cents };
}

twice(Money { cents: 150 }).cents;
300

The classes have impls for the primitive types, the numbers and Bool, for the operators each of them has, and for tuples whose elements have them; Char and String, which the prelude defines, have impls of Eq and PartialOrd. No operator is built in: a < b is always a call of the function < in scope, like the prelude's fn a < b = lt(a, b), and the impls for the primitive types call what is, like i32_lt. So an operator works for any type with an impl of its class, and only for those: comparing two closures, or two structs without an impl of Eq, is an error.

PartialOrd's lt, gt, lte and gte have defaults from partial_cmp, so an impl only needs that:

struct Version { major: i32, minor: i32 }

impl PartialOrd[Version] {
fn partial_cmp(a, b) = match partial_cmp(a.major, b.major) {
Some(Ordering.Equal) => partial_cmp(a.minor, b.minor),
other => other,
};
}

Version { major: 1, minor: 2 } < Version { major: 1, minor: 10 };
True

Strings are joined with <>, of Semigroup, rather than with +.

Classes of type constructors​

A class can also be for type constructors like Option or List: types that still need an argument. The prelude's Functor is the class of containers whose contents can be transformed with a function:

class Mappable[F] {
fn map_all[A, B](f: fn (A) -> B, x: F[A]) -> F[B];
}

impl Mappable[Option] {
fn map_all[A, B](f: fn (A) -> B, x: Option[A]) -> Option[B] = match x {
Some(a) => Some(f(a)),
None => None,
};
}

let doubled: Option[i32] = map_all(|n| n * 2, Some(21));

F[A] applies F to A, so F must be something that takes a type, like Option. Bolt works this out by itself from how F is used. The impl is for Option on its own, without an argument, and inside it F[A] becomes Option[A].

A constructor that takes two types, like a Result[E, A], can be given its first one: impl[E] Mappable[Result[E]] maps the successful values and leaves the errors alone.

Using a type that doesn't take an argument there is an error:

class Mappable[F] {
fn map_all[A, B](f: fn (A) -> B, x: F[A]) -> F[B];
}

impl Mappable[i32] {
fn map_all(f, x) = x;
}
[E0216] Error: expected a type of kind `Type -> Type`, found `i32` of kind `Type`

A kind is the type of a type: i32 is a Type, and Option is a Type -> Type, which gives a Type when it's given one.

Next: modules.