manpagez: man pages & more
info bigloo
Home | html | info | man
[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.3 Generic functions

A generic function is a bag of specific functions known as methods. When invoked on a Bigloo object, a generic function determines the class of the discriminating variable (corresponding to the first argument of the generic function) and invokes the appropriate method. Generic functions implement single inheritance and each is defined using the define-generic Bigloo syntax.

bigloo syntax: define-generic (name arg…) default-body

A generic function can be defined with a default body which will be evaluated if no method can be found for the discriminating variable. The default default-body signals an error.

As an example, here is a possible definition of the object-display generic function:

(define-generic (object-display obj::object . op)
   (let ((port (if (pair? op) 
                   (car op) 
                   (current-output-port))))
      (display "#\|" port)
      (display (class-name (object-class obj)) port)
      (display "\|" port)))

Methods can be defined to specialize a generic function and such methods must have a compatible variable list. That is, the first argument of the method must be a sub-type (i.e. belong to a sub-class) of the first argument of the generic function. Other formal parameters must be of same types. Moreover, the result type of the method must be a sub-type of the result of the generic function.

bigloo syntax: define-method (name arg…) body
bigloo syntax: call-next-method

If there is no appropriate method, an error is signaled.

Methods can use the form (call-next-method) to invoke the method that would have been called if not present. The (call-next-method) cannot be used out of method definition. example:

(define-method (object-display p::person . op)
   (let ((port (if (pair? op) 
                   (car op) 
                   (current-output-port))))
      (fprint port "firstname : " (-> p fname))
      (fprint port "name      : " (-> p name))
      (fprint port "sex       : " (-> p sex))
      p))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on March 31, 2014 using texi2html 5.0.

© manpagez.com 2000-2024
Individual documents may contain additional copyright information.