derive is a top-level attribute that automatically generates type class instances for a define-type or define-struct.
Syntax
(derive ⟨class-name⟩+)
Semantics
derivemust appear immediately before adefine-typeordefine-struct(or separated from it only by areprattribute). At most onederiveattribute may be attached to a definition.- The target type must have at least one constructor.
- For each listed
⟨class-name⟩, Coalton synthesizes adefine-instancefor(⟨class-name⟩ ⟨type⟩)whose context requires(⟨class-name⟩ ⟨field-type⟩)for every constructor or struct field type⟨field-type⟩. - Built-in derivable classes in the standard library:
Eq: Implements==by checking that two values have the same constructor and recursively comparing corresponding fields left-to-right with==.Hash: Implementshashby seeding a constructor-specific hash from the type name and constructor name, then folding each field’shashwithcoalton/hash:combine-hashes.Default: Implementsdefaultfor single-constructor types and structs by calling(default)for every field. (Rejects sum types with multiple constructors.)Show: Implementsshow-toby formatting nullary constructors as"Ctor"and constructors with fields as"(Ctor field1 field2 ...)".
Examples
(coalton-toplevel
(derive Eq Hash Default Show)
(define-struct (Point :a)
(x :a)
(y :a))
(derive Eq Show)
(define-type (Shape :a)
(Circle (Point :a) :a)
(Rectangle (Point :a) (Point :a))))
(coalton
(progn
(let p = (the (Point Integer) (default)))
(== p (Point 0 0))))
; => COMMON-LISP:T
Other Notes
- Custom type classes can support
deriveby defining a Common Lisp method on the generic functioncoalton-impl/typechecker:derive-methodsEQL-specialized on the class symbol. define-exception,define-resumption, anddefine-type-aliasdo not acceptderive.