9. Type classes and reusable interfaces
A type class is a structure whose values Lean can infer automatically when used as instance arguments. It packages operations and sometimes laws required by a generic definition, much like an interface or trait. During elaboration, instance search uses the available instances to fill in a missing term.
class Label (α : Type) where
label : α → String
structure AccountId where
value : Nat
instance : Label AccountId where
label id := s!"account-{id.value}"
def display {α : Type} [Label α] (x : α) : String :=
Label.label x
#eval display (AccountId.mk 17)
The bracketed parameter [Label α] asks Lean to find a Label instance for α. Lean infers the ordinary implicit parameter {α} from type constraints. Even when Lean knows α, instance search can fail if no suitable instance exists.
Separate an operation from its laws
BEq α supplies a Boolean comparison. A lawful interface also provides evidence that the comparison agrees with propositional equality. Generic proofs can use that evidence when reasoning about an overloaded operation.
You can define laws directly in a class:
class HasDefault (α : Type) where
value : α
class DefaultIsZero (α : Type) [OfNat α 0] [HasDefault α] : Prop where
valid : HasDefault.value (α := α) = 0
instance : HasDefault Nat where
value := 0
instance : DefaultIsZero Nat where
valid := rfl
example : HasDefault.value (α := Nat) = 0 :=
DefaultIsZero.valid
The operation class produces data. The law class lives in Prop and supplies evidence. Larger libraries use this separation so algorithms can require only the operations they execute, while theorems request the laws they use.
Read common interfaces
Repr supports debugging output. ToString supports presentation as a string. OfNat interprets numeric literals.
HAdd supports addition, including operations with different input and output types. Functor, Applicative, and Monad describe increasingly expressive ways to organise computations.
A coercion allows Lean to insert a conversion in an expected context. This lets code use a value in a context that expects a different type. If a call becomes unclear, add a type annotation and inspect the inserted conversion with editor information or pretty-printing options.
Use a local instance when its interpretation is specific to a proof or module. Several global instances for the same type and interface can make the selected behaviour depend on priorities and imports. For application-specific meanings, a wrapper type often gives clearer instance selection.
Exercises
- Define a
Labelinstance for a newUserIdstructure. - Explain why implementing
BEqby always returningtruedoes not prove all values equal. - Write a generic function that returns 2 copies of
HasDefault.valuein a pair.