4.4 Generic Interfaces
(require racket/generic) |
A generic interface allows per-type methods to be associated with generic functions. Generic functions are defined using a define-generics form. Method implementations for a structure type are defined using the #:methods keyword (see Defining Structure Types: struct).
syntax
(define-generics id [#:defined-table defined-table-id] [method-id . kw-formals*] ... maybe-defaults)
kw-formals* = (arg* ...) | (arg* ...+ . rest-id) | rest-id arg* = arg-id | [arg-id] | keyword arg-id | keyword [arg-id] maybe-defaults =
|
#:defaults ([pred? method-impl ...] ...)
gen:id as a transformer binding for the static information about a new generic interface;
id? as a predicate identifying instances of structure types that implement this generic group; and
each method-id as a generic procedure that calls the corresponding method on values where id? is true.
id/c as a contract combinator that recognizes instances of structure types which implement the gen:id generic interface. The combinator takes pairs of method-ids and contracts. The contracts will be applied to each of the corresponding method implementations.
Each method-id’s kw-formals* must include a required by-position argument that is free-identifier=? to id. That argument is used in the generic definition to locate the specialization.
When defined-table-id is provided, it is defined as a procedure that takes an instance of the generics and returns an immutable hash table that maps symbols corresponding to method names to booleans representing whether or not that method is implemented by the instance. This table is intended for use by higher-level APIs to adapt their behavior depending on method availability.
When maybe-defaults is provided, each generic function uses pred?s to dispatch to the given default implementations, method-impls, before dispatching to the generic method table. The syntax of the method-impls is the same as the methods provided for the #:methods keyword for struct.
The id/c combinator is intended to be used to contract the range of a constructor procedure for a struct type that implements the generic interface.
syntax
(define/generic local-id method-id)
local-id : identifier?
method-id : identifier?
Using the define/generic form outside a #:methods specification in struct (or define-struct) is an syntax error.
Examples: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|