chickadee » tinyclos » define-method

(define-method (NAME (VARIABLE1 CLASS1) ... ARGUMENT ...) BODY ...)syntax

Adds a new method with the code BODY ... to the generic function bound to NAME.

CLASS1 ... is a list if classes that specialize this particular method.

The method can have additional ARGUMENTS, which do not specialize the method any further. Extended lambda-lists are allowed (argument lists with #!optional, #!key, and/or #!rest), but cannot be specialized.

Inside the BODY ... of the method the identifier call-next-method names a procedure of zero arguments that can be invoked to call the next applicable method with the same arguments.

; Create new generic
(define-generic square-number?)

; Provide a method to operate on integers
(define-method (square-number? (n <integer>))
  (and (positive? n)
    (let ((sq (truncate (sqrt n))))
      (= (* sq sq) n))))

; Provide a method to operate on inexact numbers
(define-method (square-number? (n <inexact>)) #f)

This example also shows that generics can be used without creating classes. It exploits the primitive class system of TinyCLOS, in which all Scheme objects are members of a built-in class hierarchy.

It is an error to use define-method if no generic function is bound to NAME. This is a change from previous versions of TinyCLOS.

Currently methods defined with define-method should not be hidden (via (declare (hide ...)), nor should such files be compiled in block mode, unless the methods are exported.