3 ms·
A typeclass (or in Rust, a trait) is something that describes a set of behaviours that must be implemented by a type (in OOP languages, abstract classes are bro
by zesterer 4y ago
A typeclass (or in Rust, a trait) is something that describes a set of behaviours that must be implemented by a type (in OOP languages, abstract classes are broadly equivalent).
For example, the typeclass `Eq` describes how values of a type might be compared for equality.
class Eq =
=> eq : Self -> Self -> Bool
The typeclass requires that types conforming to it provide a function, `eq`, that takes two instances of itself and returns a bool (indicating whether the instances are equal). And member of this typeclass might look like:
for A, B member (A, B) of Eq where
A < Eq,
B < Eq,
=
=> eq = fn (a0, b0), (b0, b1) => a0 == a1 && b0 == b1
You can read this as "for any two types, A and B, a tuple of both can also be compared for equality provided both A and B can themselves be compared for equality"
Typeclasses become useful because they allow you to constrain generic type parameters. For example, we can now write a function that determines whether a list contains a matching value:
fn contains A : A -> [A] -> Bool where
A < Eq,
=
| _, [] => False
\ k, [x .. xs] => x == k || xs->contains(k)
All of this is checked at compile-time by the compiler, ensuring that the function can only be called with types that can be compared for equality.