1 @c Original attribution:
4 @c STk Reference manual (Appendix: An Introduction to STklos)
6 @c Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
7 @c Permission to use, copy, modify, distribute,and license this
8 @c software and its documentation for any purpose is hereby granted,
9 @c provided that existing copyright notices are retained in all
10 @c copies and that this notice is included verbatim in any
11 @c distributions. No written agreement, license, or royalty fee is
12 @c required for any of the authorized uses.
13 @c This software is provided ``AS IS'' without express or implied
17 @c Adapted for use in Guile with the authors permission
19 @c @macro goops @c was {\stklos}
23 @c @macro guile @c was {\stk}
27 This is chapter was originally written by Erick Gallesio as an appendix
28 for the STk reference manual, and subsequently adapted to @goops{}.
33 * Class definition and instantiation::
38 @node Copyright, Intro, Tutorial, Tutorial
43 STk Reference manual (Appendix: An Introduction to STklos)
45 Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@@unice.fr>
46 Permission to use, copy, modify, distribute,and license this
47 software and its documentation for any purpose is hereby granted,
48 provided that existing copyright notices are retained in all
49 copies and that this notice is included verbatim in any
50 distributions. No written agreement, license, or royalty fee is
51 required for any of the authorized uses.
52 This software is provided ``AS IS'' without express or implied
55 Adapted for use in Guile with the authors permission
57 @node Intro, Class definition and instantiation, Copyright, Tutorial
60 @goops{} is the object oriented extension to @guile{}. Its
61 implementation is derived from @w{STk-3.99.3} by Erick Gallesio and
62 version 1.3 of the Gregor Kiczales @cite{Tiny-Clos}. It is very close
63 to CLOS, the Common Lisp Object System (@cite{CLtL2}) but is adapted for
66 Briefly stated, the @goops{} extension gives the user a full object
67 oriented system with multiple inheritance and generic functions with
68 multi-method dispatch. Furthermore, the implementation relies on a true
69 meta object protocol, in the spirit of the one defined for CLOS
70 (@cite{Gregor Kiczales: A Metaobject Protocol}).
72 The purpose of this tutorial is to introduce briefly the @goops{}
73 package and in no case will it replace the @goops{} reference manual
74 (which needs to be urgently written now@ @dots{}).
76 Note that the operations described in this tutorial resides in modules
77 that may need to be imported before being available. The main module is
78 imported by evaluating:
81 (use-modules (oop goops))
88 @node Class definition and instantiation, Inheritance, Intro, Tutorial
89 @section Class definition and instantiation
95 @node Class definition, , Class definition and instantiation, Class definition and instantiation
96 @subsection Class definition
98 A new class is defined with the @code{define-class}@footnote{Don't
99 forget to import the @code{(oop goops)} module} macro. The syntax of
100 @code{define-class} is close to CLOS @code{defclass}:
105 (define-class @var{class} (@var{superclass} @dots{})
106 @var{slot-description} @dots{}
107 @var{class-option} @dots{})
110 Class options will not be discussed in this tutorial. The list of
111 @var{superclass}es specifies which classes to inherit properties from
112 @var{class} (see @ref{Inheritance} for more details). A
113 @var{slot-description} gives the name of a slot and, eventually, some
114 ``properties'' of this slot (such as its initial value, the function
115 which permit to access its value, @dots{}). Slot descriptions will be
116 discussed in @ref{Slot description}.
119 As an example, let us define a type for representation of complex
120 numbers in terms of real numbers. This can be done with the following
124 (define-class <complex> (<number>)
128 This binds the variable @code{<complex>}@footnote{@code{<complex>} is in
129 fact a builtin class in GOOPS. Because of this, GOOPS will create a new
130 class. The old class will still serve as the type for Guile's native
131 complex numbers.} to a new class whose instances contain two
132 slots. These slots are called @code{r} an @code{i} and we suppose here
133 that they contain respectively the real part and the imaginary part of a
134 complex number. Note that this class inherits from @code{<number>} which
135 is a pre-defined class. (@code{<number>} is the direct super class of
136 the pre-defined class @code{<complex>} which, in turn, is the super
137 class of @code{<real>} which is the super of
138 @code{<integer>}.)@footnote{With the new definition of @code{<complex>},
139 a @code{<real>} is not a @code{<complex>} since @code{<real>} inherits
140 from @code{ <number>} rather than @code{<complex>}. In practice,
141 inheritance could be modified @emph{a posteriori}, if needed. However,
142 this necessitates some knowledge of the meta object protocol and it will
143 not be shown in this document}.
145 @node Inheritance, Generic functions, Class definition and instantiation, Tutorial
147 @c \label{inheritance}
150 * Class hierarchy and inheritance of slots::
151 * Instance creation and slot access::
153 * Class precedence list::
156 @node Class hierarchy and inheritance of slots, Instance creation and slot access, Inheritance, Inheritance
157 @subsection Class hierarchy and inheritance of slots
158 Inheritance is specified upon class definition. As said in the
159 introduction, @goops{} supports multiple inheritance. Here are some
163 (define-class A () a)
164 (define-class B () b)
165 (define-class C () c)
166 (define-class D (A B) d a)
167 (define-class E (A C) e c)
168 (define-class F (D E) f)
171 @code{A}, @code{B}, @code{C} have a null list of super classes. In this
172 case, the system will replace it by the list which only contains
173 @code{<object>}, the root of all the classes defined by
174 @code{define-class}. @code{D}, @code{E}, @code{F} use multiple
175 inheritance: each class inherits from two previously defined classes.
176 Those class definitions define a hierarchy which is shown in Figure@ 1.
177 In this figure, the class @code{<top>} is also shown; this class is the
178 super class of all Scheme objects. In particular, @code{<top>} is the
179 super class of all standard Scheme types.
184 @center @emph{Fig 1: A class hierarchy}
186 @emph{(@code{<complex>} which is the direct subclass of @code{<number>}
187 and the direct superclass of @code{<real>} has been omitted in this
193 The set of slots of a given class is calculated by taking the union of the
194 slots of all its super class. For instance, each instance of the class
195 D, defined before will have three slots (@code{a}, @code{b} and
196 @code{d}). The slots of a class can be obtained by the @code{class-slots}
197 primitive. For instance,
200 (class-slots A) @result{} ((a))
201 (class-slots E) @result{} ((a) (e) (c))
202 (class-slots F) @result{} ((e) (c) (b) (d) (a) (f))
203 @c used to be ((d) (a) (b) (c) (f))
206 @emph{Note: } The order of slots is not significant.
208 @node Instance creation and slot access, Slot description, Class hierarchy and inheritance of slots, Inheritance
209 @subsection Instance creation and slot access
211 Creation of an instance of a previously defined
212 class can be done with the @code{make} procedure. This
213 procedure takes one mandatory parameter which is the class of the
214 instance which must be created and a list of optional
215 arguments. Optional arguments are generally used to initialize some
216 slots of the newly created instance. For instance, the following form
221 (define c (make <complex>))
224 will create a new @code{<complex>} object and will bind it to the @code{c}
227 Accessing the slots of the new complex number can be done with the
228 @code{slot-ref} and the @code{slot-set!} primitives. @code{Slot-set!}
229 primitive permits to set the value of an object slot and @code{slot-ref}
230 permits to get its value.
238 (slot-ref c 'r) @result{} 10
239 (slot-ref c 'i) @result{} 3
243 Using the @code{describe} function is a simple way to see all the
244 slots of an object at one time: this function prints all the slots of an
245 object on the standard output.
247 First load the module @code{(oop goops describe)}:
250 @code{(use-modules (oop goops describe))}
259 will now print the following information on the standard output:
262 #<<complex> 401d8638> is an instance of class <complex>
268 @node Slot description, Class precedence list, Instance creation and slot access, Inheritance
269 @subsection Slot description
270 @c \label{slot-description}
272 When specifying a slot, a set of options can be given to the
273 system. Each option is specified with a keyword. The list of authorized
274 keywords is given below:
279 @code{#:init-value} permits to supply a default value for the slot. This
280 default value is obtained by evaluating the form given after the
281 @code{#:init-form} in the global environment, at class definition time.
282 @cindex default slot value
284 @cindex top level environment
287 @code{#:init-thunk} permits to supply a thunk that will provide a
288 default value for the slot. The value is obtained by evaluating the
289 thunk a instance creation time.
290 @c CHECKME: in the global environment?
291 @findex default slot value
293 @cindex top level environment
296 @code{#:init-keyword} permits to specify the keyword for initializing a
297 slot. The init-keyword may be provided during instance creation (i.e. in
298 the @code{make} optional parameter list). Specifying such a keyword
299 during instance initialization will supersede the default slot
300 initialization possibly given with @code{#:init-form}.
301 @findex #:init-keyword
304 @code{#:getter} permits to supply the name for the
305 slot getter. The name binding is done in the
306 environment of the @code{define-class} macro.
308 @cindex top level environment
312 @code{#:setter} permits to supply the name for the
313 slot setter. The name binding is done in the
314 environment of the @code{define-class} macro.
316 @cindex top level environment
320 @code{#:accessor} permits to supply the name for the
321 slot accessor. The name binding is done in the global
322 environment. An accessor permits to get and
323 set the value of a slot. Setting the value of a slot is done with the extended
324 version of @code{set!}.
327 @cindex top level environment
331 @code{#:allocation} permits to specify how storage for
332 the slot is allocated. Three kinds of allocation are provided.
333 They are described below:
337 @code{#:instance} indicates that each instance gets its own storage for
338 the slot. This is the default.
340 @code{#:class} indicates that there is one storage location used by all
341 the direct and indirect instances of the class. This permits to define a
342 kind of global variable which can be accessed only by (in)direct
343 instances of the class which defines this slot.
345 @code{#:each-subclass} indicates that there is one storage location used
346 by all the direct instances of the class. In other words, if two classes
347 are not siblings in the class hierarchy, they will not see the same
350 @code{#:virtual} indicates that no storage will be allocated for this
351 slot. It is up to the user to define a getter and a setter function for
352 this slot. Those functions must be defined with the @code{#:slot-ref}
353 and @code{#:slot-set!} options. See the example below.
358 @findex #:each-subclass
364 To illustrate slot description, we shall redefine the @code{<complex>} class
365 seen before. A definition could be:
368 (define-class <complex> (<number>)
369 (r #:init-value 0 #:getter get-r #:setter set-r! #:init-keyword #:r)
370 (i #:init-value 0 #:getter get-i #:setter set-i! #:init-keyword #:i))
373 With this definition, the @code{r} and @code{i} slot are set to 0 by
374 default. Value of a slot can also be specified by calling @code{make}
375 with the @code{#:r} and @code{#:i} keywords. Furthermore, the generic
376 functions @code{get-r} and @code{set-r!} (resp. @code{get-i} and
377 @code{set-i!}) are automatically defined by the system to read and write
378 the @code{r} (resp. @code{i}) slot.
381 (define c1 (make <complex> #:r 1 #:i 2))
382 (get-r c1) @result{} 1
384 (get-r c1) @result{} 12
385 (define c2 (make <complex> #:r 2))
386 (get-r c2) @result{} 2
387 (get-i c2) @result{} 0
390 Accessors provide an uniform access for reading and writing an object
391 slot. Writing a slot is done with an extended form of @code{set!}
392 which is close to the Common Lisp @code{setf} macro. So, another
393 definition of the previous @code{<complex>} class, using the
394 @code{#:accessor} option, could be:
398 (define-class <complex> (<number>)
399 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
400 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i))
403 Using this class definition, reading the real part of the @code{c}
404 complex can be done with:
408 and setting it to the value contained in the @code{new-value} variable
409 can be done using the extended form of @code{set!}.
411 (set! (real-part c) new-value)
414 Suppose now that we have to manipulate complex numbers with rectangular
415 coordinates as well as with polar coordinates. One solution could be to
416 have a definition of complex numbers which uses one particular
417 representation and some conversion functions to pass from one
418 representation to the other. A better solution uses virtual slots. A
419 complete definition of the @code{<complex>} class using virtual slots is
425 (define-class <complex> (<number>)
426 ;; True slots use rectangular coordinates
427 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
428 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i)
429 ;; Virtual slots access do the conversion
430 (m #:accessor magnitude #:init-keyword #:magn
431 #:allocation #:virtual
432 #:slot-ref (lambda (o)
433 (let ((r (slot-ref o 'r)) (i (slot-ref o 'i)))
434 (sqrt (+ (* r r) (* i i)))))
435 #:slot-set! (lambda (o m)
436 (let ((a (slot-ref o 'a)))
437 (slot-set! o 'r (* m (cos a)))
438 (slot-set! o 'i (* m (sin a))))))
439 (a #:accessor angle #:init-keyword #:angle
440 #:allocation #:virtual
441 #:slot-ref (lambda (o)
442 (atan (slot-ref o 'i) (slot-ref o 'r)))
443 #:slot-set! (lambda(o a)
444 (let ((m (slot-ref o 'm)))
445 (slot-set! o 'r (* m (cos a)))
446 (slot-set! o 'i (* m (sin a)))))))
449 @center @emph{Fig 2: A @code{<complex>} number class definition using virtual slots}
454 This class definition implements two real slots (@code{r} and
455 @code{i}). Values of the @code{m} and @code{a} virtual slots are
456 calculated from real slot values. Reading a virtual slot leads to the
457 application of the function defined in the @code{#:slot-ref}
458 option. Writing such a slot leads to the application of the function
459 defined in the @code{#:slot-set!} option. For instance, the following
468 permits to set the angle of the @code{c} complex number. This expression
469 conducts, in fact, to the evaluation of the following expression
473 (let ((m (slot-ref o 'm)))
474 (slot-set! o 'r (* m (cos a)))
475 (slot-set! o 'i (* m (sin a))))
479 A more complete example is given below:
484 (define c (make <complex> #:r 12 #:i 20))
485 (real-part c) @result{} 12
486 (angle c) @result{} 1.03037682652431
488 (set! (real-part c) 1)
489 (describe c) @result{}
490 #<<complex> 401e9b58> is an instance of class <complex>
500 Since initialization keywords have been defined for the four slots, we
501 can now define the @code{make-rectangular} and @code{make-polar} standard
505 (define make-rectangular
506 (lambda (x y) (make <complex> #:r x #:i y)))
509 (lambda (x y) (make <complex> #:magn x #:angle y)))
512 @node Class precedence list, , Slot description, Inheritance
513 @subsection Class precedence list
515 A class may have more than one superclass. @footnote{This section is an
516 adaptation of Jeff Dalton's (J.Dalton@@ed.ac.uk) @cite{Brief
517 introduction to CLOS}} With single inheritance (one superclass), it is
518 easy to order the super classes from most to least specific. This is the
523 Rule 1: Each class is more specific than its superclasses.@c was \bf
527 With multiple inheritance, ordering is harder. Suppose we have
536 (define-class Z (X Y)
540 In this case, the @code{Z} class is more specific than the @code{X} or
541 @code{Y} class for instances of @code{Z}. However, the @code{#:init-value}
542 specified in @code{X} and @code{Y} leads to a problem: which one
543 overrides the other? The rule in @goops{}, as in CLOS, is that the
544 superclasses listed earlier are more specific than those listed later.
549 Rule 2: For a given class, superclasses listed earlier are more
550 specific than those listed later.
554 These rules are used to compute a linear order for a class and all its
555 superclasses, from most specific to least specific. This order is
556 called the ``class precedence list'' of the class. Given these two
557 rules, we can claim that the initial form for the @code{x} slot of
558 previous example is 1 since the class @code{X} is placed before @code{Y}
559 in class precedence list of @code{Z}.
561 These two rules are not always enough to determine a unique order,
562 however, but they give an idea of how things work. Taking the @code{F}
563 class shown in Figure@ 1, the class precedence list is
566 (f d e a c b <object> <top>)
569 However, it is usually considered a bad idea for programmers to rely on
570 exactly what the order is. If the order for some superclasses is important,
571 it can be expressed directly in the class definition.
573 The precedence list of a class can be obtained by the function
574 @code{class-precedence-list}. This function returns a ordered
575 list whose first element is the most specific class. For instance,
578 (class-precedence-list B) @result{} (#<<class> B 401b97c8>
579 #<<class> <object> 401e4a10>
580 #<<class> <top> 4026a9d8>)
583 However, this result is not too much readable; using the function
584 @code{class-name} yields a clearer result:
587 (map class-name (class-precedence-list B)) @result{} (B <object> <top>)
590 @node Generic functions, , Inheritance, Tutorial
591 @section Generic functions
594 * Generic functions and methods::
599 @node Generic functions and methods, Next-method, Generic functions, Generic functions
600 @subsection Generic functions and methods
602 @c \label{gf-n-methods}
603 Neither @goops{} nor CLOS use the message mechanism for methods as most
604 Object Oriented language do. Instead, they use the notion of
605 @dfn{generic functions}. A generic function can be seen as a methods
606 ``tanker''. When the evaluator requested the application of a generic
607 function, all the methods of this generic function will be grabbed and
608 the most specific among them will be applied. We say that a method
609 @var{M} is @emph{more specific} than a method @var{M'} if the class of
610 its parameters are more specific than the @var{M'} ones. To be more
611 precise, when a generic function must be ``called'' the system will:
613 @cindex generic function
616 search among all the generic function those which are applicable
618 sort the list of applicable methods in the ``most specific'' order
620 call the most specific method of this list (i.e. the first method of
621 the sorted methods list).
624 The definition of a generic function is done with the
625 @code{define-generic} macro. Definition of a new method is done with the
626 @code{define-method} macro. Note that @code{define-method} automatically
627 defines the generic function if it has not been defined
628 before. Consequently, most of the time, the @code{define-generic} needs
630 @findex define-generic
631 @findex define-method
632 Consider the following definitions:
636 (define-method (G (a <integer>) b) 'integer)
637 (define-method (G (a <real>) b) 'real)
638 (define-method (G a b) 'top)
641 The @code{define-generic} call defines @var{G} as a generic
642 function. Note that the signature of the generic function is not given
643 upon definition, contrarily to CLOS. This will permit methods with
644 different signatures for a given generic function, as we shall see
645 later. The three next lines define methods for the @var{G} generic
646 function. Each method uses a sequence of @dfn{parameter specializers}
647 that specify when the given method is applicable. A specializer permits
648 to indicate the class a parameter must belong to (directly or
649 indirectly) to be applicable. If no specializer is given, the system
650 defaults it to @code{<top>}. Thus, the first method definition is
653 @cindex parameter specializers
655 (define-method (G (a <integer>) (b <top>)) 'integer)
658 Now, let us look at some possible calls to generic function @var{G}:
661 (G 2 3) @result{} integer
662 (G 2 #t) @result{} integer
663 (G 1.2 'a) @result{} real
664 @c (G #3 'a) @result{} real @c was {\sharpsign}
665 (G #t #f) @result{} top
666 (G 1 2 3) @result{} error (since no method exists for 3 parameters)
669 The preceding methods use only one specializer per parameter list. Of
670 course, each parameter can use a specializer. In this case, the
671 parameter list is scanned from left to right to determine the
672 applicability of a method. Suppose we declare now
675 (define-method (G (a <integer>) (b <number>)) 'integer-number)
676 (define-method (G (a <integer>) (b <real>)) 'integer-real)
677 (define-method (G (a <integer>) (b <integer>)) 'integer-integer)
678 (define-method (G a (b <number>)) 'top-number)
684 (G 1 2) @result{} integer-integer
685 (G 1 1.0) @result{} integer-real
686 (G 1 #t) @result{} integer
687 (G 'a 1) @result{} top-number
690 @node Next-method, Example, Generic functions and methods, Generic functions
691 @subsection Next-method
693 When you call a generic function, with a particular set of arguments,
694 GOOPS builds a list of all the methods that are applicable to those
695 arguments and orders them by how closely the method definitions match
696 the actual argument types. It then calls the method at the top of this
697 list. If the selected method's code wants to call on to the next method
698 in this list, it can do so by using @code{next-method}.
701 (define-method (Test (a <integer>)) (cons 'integer (next-method)))
702 (define-method (Test (a <number>)) (cons 'number (next-method)))
703 (define-method (Test a) (list 'top))
706 With these definitions,
709 (Test 1) @result{} (integer number top)
710 (Test 1.0) @result{} (number top)
711 (Test #t) @result{} (top)
714 @code{next-method} is always called as just @code{(next-method)}. The
715 arguments for the next method call are always implicit, and always the
716 same as for the original method call.
718 If you want to call on to a method with the same name but with a
719 different set of arguments (as you might with overloaded methods in C++,
720 for example), you do not use @code{next-method}, but instead simply
721 write the new call as usual:
724 (define-method (Test (a <number>) min max)
725 (if (and (>= a min) (<= a max))
726 (display "Number is in range\n"))
736 (You should be careful in this case that the @code{Test} calls do not
737 lead to an infinite recursion, but this consideration is just the same
738 as in Scheme code in general.)
740 @node Example, , Next-method, Generic functions
743 In this section we shall continue to define operations on the @code{<complex>}
744 class defined in Figure@ 2. Suppose that we want to use it to implement
745 complex numbers completely. For instance a definition for the addition of
746 two complexes could be
749 (define-method (new-+ (a <complex>) (b <complex>))
750 (make-rectangular (+ (real-part a) (real-part b))
751 (+ (imag-part a) (imag-part b))))
754 To be sure that the @code{+} used in the method @code{new-+} is the standard
758 (define-generic new-+)
761 (define-method (new-+ (a <complex>) (b <complex>))
762 (make-rectangular (+ (real-part a) (real-part b))
763 (+ (imag-part a) (imag-part b)))))
766 The @code{define-generic} ensures here that @code{new-+} will be defined
767 in the global environment. Once this is done, we can add methods to the
768 generic function @code{new-+} which make a closure on the @code{+}
769 symbol. A complete writing of the @code{new-+} methods is shown in
775 (define-generic new-+)
779 (define-method (new-+ (a <real>) (b <real>)) (+ a b))
781 (define-method (new-+ (a <real>) (b <complex>))
782 (make-rectangular (+ a (real-part b)) (imag-part b)))
784 (define-method (new-+ (a <complex>) (b <real>))
785 (make-rectangular (+ (real-part a) b) (imag-part a)))
787 (define-method (new-+ (a <complex>) (b <complex>))
788 (make-rectangular (+ (real-part a) (real-part b))
789 (+ (imag-part a) (imag-part b))))
791 (define-method (new-+ (a <number>)) a)
793 (define-method (new-+) 0)
795 (define-method (new-+ . args)
797 (apply new-+ (cdr args)))))
802 @center @emph{Fig 3: Extending @code{+} for dealing with complex numbers}
807 We use here the fact that generic function are not obliged to have the
808 same number of parameters, contrarily to CLOS. The four first methods
809 implement the dyadic addition. The fifth method says that the addition
810 of a single element is this element itself. The sixth method says that
811 using the addition with no parameter always return 0. The last method
812 takes an arbitrary number of parameters@footnote{The parameter list for
813 a @code{define-method} follows the conventions used for Scheme
814 procedures. In particular it can use the dot notation or a symbol to
815 denote an arbitrary number of parameters}. This method acts as a kind
816 of @code{reduce}: it calls the dyadic addition on the @emph{car} of the
817 list and on the result of applying it on its rest. To finish, the
818 @code{set!} permits to redefine the @code{+} symbol to our extended
822 To terminate our implementation (integration?) of complex numbers, we can
823 redefine standard Scheme predicates in the following manner:
826 (define-method (complex? c <complex>) #t)
827 (define-method (complex? c) #f)
829 (define-method (number? n <number>) #t)
830 (define-method (number? n) #f)
835 Standard primitives in which complex numbers are involved could also be
836 redefined in the same manner.