2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 2008, 2009
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @c Original attribution:
10 @c STk Reference manual (Appendix: An Introduction to STklos)
12 @c Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
13 @c Permission to use, copy, modify, distribute,and license this
14 @c software and its documentation for any purpose is hereby granted,
15 @c provided that existing copyright notices are retained in all
16 @c copies and that this notice is included verbatim in any
17 @c distributions. No written agreement, license, or royalty fee is
18 @c required for any of the authorized uses.
19 @c This software is provided ``AS IS'' without express or implied
23 @c Adapted for use in Guile with the authors permission
25 @c @macro goops @c was {\stklos}
29 @c @macro guile @c was {\stk}
33 This section introduces the @goops{} package in more detail. It was
34 originally written by Erick Gallesio as an appendix for the STk
35 reference manual, and subsequently adapted to @goops{}.
37 The procedures and syntax described in this tutorial are provided by
38 Guile modules that may need to be imported before being available.
39 The main @goops{} module is imported by evaluating:
42 (use-modules (oop goops))
52 * Instance creation and slot access::
63 STk Reference manual (Appendix: An Introduction to STklos)
65 Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@@unice.fr>
66 Permission to use, copy, modify, distribute,and license this
67 software and its documentation for any purpose is hereby granted,
68 provided that existing copyright notices are retained in all
69 copies and that this notice is included verbatim in any
70 distributions. No written agreement, license, or royalty fee is
71 required for any of the authorized uses.
72 This software is provided ``AS IS'' without express or implied
75 Adapted for use in Guile with the author's permission
77 @node Class definition
78 @subsection Class definition
80 A new class is defined with the @code{define-class} macro. The syntax
81 of @code{define-class} is close to CLOS @code{defclass}:
86 (define-class @var{class} (@var{superclass} @dots{})
87 @var{slot-description} @dots{}
88 @var{class-option} @dots{})
91 @var{class} is the class being defined. The list of
92 @var{superclass}es specifies which existing classes, if any, to
93 inherit slots and properties from. Each @var{slot-description} gives
94 the name of a slot and optionally some ``properties'' of this slot;
95 for example its initial value, the name of a function which will
96 access its value, and so on. Slot descriptions and inheritance are
97 discussed more below. For class options, see @ref{Class Options}.
100 As an example, let us define a type for representing a complex number
101 in terms of two real numbers.@footnote{Of course Guile already
102 provides complex numbers, and @code{<complex>} is in fact a predefined
103 class in GOOPS; but the definition here is still useful as an
104 example.} This can be done with the following class definition:
107 (define-class <my-complex> (<number>)
111 This binds the variable @code{<my-complex>} to a new class whose
112 instances will contain two slots. These slots are called @code{r} and
113 @code{i} and will hold the real and imaginary parts of a complex
114 number. Note that this class inherits from @code{<number>}, which is a
115 predefined class.@footnote{@code{<number>} is the direct superclass of
116 the predefined class @code{<complex>}; @code{<complex>} is the
117 superclass of @code{<real>}, and @code{<real>} is the superclass of
120 @node Instance creation and slot access
121 @subsection Instance creation and slot access
123 Creation of an instance of a previously defined
124 class can be done with the @code{make} procedure. This
125 procedure takes one mandatory parameter which is the class of the
126 instance which must be created and a list of optional
127 arguments. Optional arguments are generally used to initialize some
128 slots of the newly created instance. For instance, the following form
133 (define c (make <my-complex>))
137 will create a new @code{<my-complex>} object and will bind it to the @code{c}
140 Accessing the slots of the new complex number can be done with the
141 @code{slot-ref} and the @code{slot-set!} primitives. @code{slot-set!}
142 sets the value of an object slot and @code{slot-ref} retrieves it.
150 (slot-ref c 'r) @result{} 10
151 (slot-ref c 'i) @result{} 3
155 Using the @code{describe} function is a simple way to see all the
156 slots of an object at one time: this function prints all the slots of an
157 object on the standard output.
159 First load the module @code{(oop goops describe)}:
162 @code{(use-modules (oop goops describe))}
173 will print the following information on the standard output:
176 #<<my-complex> 401d8638> is an instance of class <my-complex>
182 @node Slot description
183 @subsection Slot description
184 @c \label{slot-description}
186 When specifying a slot (in a @code{(define-class @dots{})} form),
187 various options can be specified in addition to the slot's name. Each
188 option is specified by a keyword. The list of authorized keywords is
194 @code{#:init-value} permits to supply a constant default value for the
195 slot. The value is obtained by evaluating the form given after the
196 @code{#:init-value} at class definition time.
197 @cindex default slot value
201 @code{#:init-form} specifies a form that, when evaluated, will return
202 an initial value for the slot. The form is evaluated each time that
203 an instance of the class is created, in the lexical environment of the
204 containing @code{define-class} expression.
205 @cindex default slot value
209 @code{#:init-thunk} permits to supply a thunk that will provide a
210 default value for the slot. The value is obtained by invoking the
211 thunk at instance creation time.
212 @findex default slot value
216 @code{#:init-keyword} permits to specify a keyword for initializing the
217 slot. The init-keyword may be provided during instance creation (i.e. in
218 the @code{make} optional parameter list). Specifying such a keyword
219 during instance initialization will supersede the default slot
220 initialization possibly given with @code{#:init-form}.
221 @findex #:init-keyword
224 @code{#:getter} permits to supply the name for the
225 slot getter. The name binding is done in the
226 environment of the @code{define-class} macro.
228 @cindex top level environment
232 @code{#:setter} permits to supply the name for the
233 slot setter. The name binding is done in the
234 environment of the @code{define-class} macro.
236 @cindex top level environment
240 @code{#:accessor} permits to supply the name for the
241 slot accessor. The name binding is done in the global
242 environment. An accessor permits to get and
243 set the value of a slot. Setting the value of a slot is done with the extended
244 version of @code{set!}.
247 @cindex top level environment
251 @code{#:allocation} permits to specify how storage for
252 the slot is allocated. Three kinds of allocation are provided.
253 They are described below:
257 @code{#:instance} indicates that each instance gets its own storage for
258 the slot. This is the default.
260 @code{#:class} indicates that there is one storage location used by all
261 the direct and indirect instances of the class. This permits to define a
262 kind of global variable which can be accessed only by (in)direct
263 instances of the class which defines this slot.
265 @code{#:each-subclass} indicates that there is one storage location used
266 by all the direct instances of the class. In other words, if two classes
267 are not siblings in the class hierarchy, they will not see the same
270 @code{#:virtual} indicates that no storage will be allocated for this
271 slot. It is up to the user to define a getter and a setter function for
272 this slot. Those functions must be defined with the @code{#:slot-ref}
273 and @code{#:slot-set!} options. See the example below.
278 @findex #:each-subclass
284 To illustrate slot description, we shall redefine the @code{<my-complex>} class
285 seen before. A definition could be:
288 (define-class <my-complex> (<number>)
289 (r #:init-value 0 #:getter get-r #:setter set-r! #:init-keyword #:r)
290 (i #:init-value 0 #:getter get-i #:setter set-i! #:init-keyword #:i))
293 With this definition, the @code{r} and @code{i} slot are set to 0 by
294 default. Value of a slot can also be specified by calling @code{make}
295 with the @code{#:r} and @code{#:i} keywords. Furthermore, the generic
296 functions @code{get-r} and @code{set-r!} (resp. @code{get-i} and
297 @code{set-i!}) are automatically defined by the system to read and write
298 the @code{r} (resp. @code{i}) slot.
301 (define c1 (make <my-complex> #:r 1 #:i 2))
302 (get-r c1) @result{} 1
304 (get-r c1) @result{} 12
305 (define c2 (make <my-complex> #:r 2))
306 (get-r c2) @result{} 2
307 (get-i c2) @result{} 0
310 Accessors provide an uniform access for reading and writing an object
311 slot. Writing a slot is done with an extended form of @code{set!}
312 which is close to the Common Lisp @code{setf} macro. So, another
313 definition of the previous @code{<my-complex>} class, using the
314 @code{#:accessor} option, could be:
318 (define-class <my-complex> (<number>)
319 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
320 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i))
323 Using this class definition, reading the real part of the @code{c}
324 complex can be done with:
328 and setting it to the value contained in the @code{new-value} variable
329 can be done using the extended form of @code{set!}.
331 (set! (real-part c) new-value)
334 Suppose now that we have to manipulate complex numbers with rectangular
335 coordinates as well as with polar coordinates. One solution could be to
336 have a definition of complex numbers which uses one particular
337 representation and some conversion functions to pass from one
338 representation to the other. A better solution uses virtual slots. A
339 complete definition of the @code{<my-complex>} class using virtual slots is
345 (define-class <my-complex> (<number>)
346 ;; True slots use rectangular coordinates
347 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
348 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i)
349 ;; Virtual slots access do the conversion
350 (m #:accessor magnitude #:init-keyword #:magn
351 #:allocation #:virtual
352 #:slot-ref (lambda (o)
353 (let ((r (slot-ref o 'r)) (i (slot-ref o 'i)))
354 (sqrt (+ (* r r) (* i i)))))
355 #:slot-set! (lambda (o m)
356 (let ((a (slot-ref o 'a)))
357 (slot-set! o 'r (* m (cos a)))
358 (slot-set! o 'i (* m (sin a))))))
359 (a #:accessor angle #:init-keyword #:angle
360 #:allocation #:virtual
361 #:slot-ref (lambda (o)
362 (atan (slot-ref o 'i) (slot-ref o 'r)))
363 #:slot-set! (lambda(o a)
364 (let ((m (slot-ref o 'm)))
365 (slot-set! o 'r (* m (cos a)))
366 (slot-set! o 'i (* m (sin a)))))))
369 @center @emph{Fig 2: A @code{<my-complex>} number class definition using virtual slots}
374 This class definition implements two real slots (@code{r} and
375 @code{i}). Values of the @code{m} and @code{a} virtual slots are
376 calculated from real slot values. Reading a virtual slot leads to the
377 application of the function defined in the @code{#:slot-ref}
378 option. Writing such a slot leads to the application of the function
379 defined in the @code{#:slot-set!} option. For instance, the following
388 permits to set the angle of the @code{c} complex number. This expression
389 conducts, in fact, to the evaluation of the following expression
393 (let ((m (slot-ref o 'm)))
394 (slot-set! o 'r (* m (cos a)))
395 (slot-set! o 'i (* m (sin a))))
399 A more complete example is given below:
404 (define c (make <my-complex> #:r 12 #:i 20))
405 (real-part c) @result{} 12
406 (angle c) @result{} 1.03037682652431
408 (set! (real-part c) 1)
411 #<<my-complex> 401e9b58> is an instance of class <my-complex>
421 Since initialization keywords have been defined for the four slots, we
422 can now define the @code{make-rectangular} and @code{make-polar} standard
426 (define make-rectangular
427 (lambda (x y) (make <my-complex> #:r x #:i y)))
430 (lambda (x y) (make <my-complex> #:magn x #:angle y)))
434 @subsection Inheritance
435 @c \label{inheritance}
438 * Class hierarchy and inheritance of slots::
439 * Class precedence list::
442 @node Class hierarchy and inheritance of slots
443 @subsubsection Class hierarchy and inheritance of slots
444 Inheritance is specified upon class definition. As said in the
445 introduction, @goops{} supports multiple inheritance. Here are some
449 (define-class A () a)
450 (define-class B () b)
451 (define-class C () c)
452 (define-class D (A B) d a)
453 (define-class E (A C) e c)
454 (define-class F (D E) f)
457 @code{A}, @code{B}, @code{C} have a null list of super classes. In this
458 case, the system will replace it by the list which only contains
459 @code{<object>}, the root of all the classes defined by
460 @code{define-class}. @code{D}, @code{E}, @code{F} use multiple
461 inheritance: each class inherits from two previously defined classes.
462 Those class definitions define a hierarchy which is shown in Figure@ 1.
463 In this figure, the class @code{<top>} is also shown; this class is the
464 super class of all Scheme objects. In particular, @code{<top>} is the
465 super class of all standard Scheme types.
470 @center @image{hierarchy,5in}
473 @verbatiminclude hierarchy.txt
476 @emph{Fig 1: A class hierarchy}
477 @emph{(@code{<complex>} which is the direct subclass of @code{<number>}
478 and the direct superclass of @code{<real>} has been omitted in this
483 The set of slots of a given class is calculated by taking the union of the
484 slots of all its super class. For instance, each instance of the class
485 D, defined before will have three slots (@code{a}, @code{b} and
486 @code{d}). The slots of a class can be obtained by the @code{class-slots}
487 primitive. For instance,
490 (class-slots A) @result{} ((a))
491 (class-slots E) @result{} ((a) (e) (c))
492 (class-slots F) @result{} ((e) (c) (b) (d) (a) (f))
493 @c used to be ((d) (a) (b) (c) (f))
496 @emph{Note: } The order of slots is not significant.
498 @node Class precedence list
499 @subsubsection Class precedence list
501 A class may have more than one superclass. @footnote{This section is an
502 adaptation of Jeff Dalton's (J.Dalton@@ed.ac.uk) @cite{Brief
503 introduction to CLOS}} With single inheritance (one superclass), it is
504 easy to order the super classes from most to least specific. This is the
509 Rule 1: Each class is more specific than its superclasses.@c was \bf
513 With multiple inheritance, ordering is harder. Suppose we have
522 (define-class Z (X Y)
526 In this case, the @code{Z} class is more specific than the @code{X} or
527 @code{Y} class for instances of @code{Z}. However, the @code{#:init-value}
528 specified in @code{X} and @code{Y} leads to a problem: which one
529 overrides the other? The rule in @goops{}, as in CLOS, is that the
530 superclasses listed earlier are more specific than those listed later.
535 Rule 2: For a given class, superclasses listed earlier are more
536 specific than those listed later.
540 These rules are used to compute a linear order for a class and all its
541 superclasses, from most specific to least specific. This order is
542 called the ``class precedence list'' of the class. Given these two
543 rules, we can claim that the initial form for the @code{x} slot of
544 previous example is 1 since the class @code{X} is placed before @code{Y}
545 in class precedence list of @code{Z}.
547 These two rules are not always enough to determine a unique order,
548 however, but they give an idea of how things work. Taking the @code{F}
549 class shown in Figure@ 1, the class precedence list is
552 (f d e a c b <object> <top>)
555 However, it is usually considered a bad idea for programmers to rely on
556 exactly what the order is. If the order for some superclasses is important,
557 it can be expressed directly in the class definition.
559 The precedence list of a class can be obtained by the function
560 @code{class-precedence-list}. This function returns a ordered
561 list whose first element is the most specific class. For instance,
564 (class-precedence-list B) @result{} (#<<class> B 401b97c8>
565 #<<class> <object> 401e4a10>
566 #<<class> <top> 4026a9d8>)
569 However, this result is not too much readable; using the function
570 @code{class-name} yields a clearer result:
573 (map class-name (class-precedence-list B)) @result{} (B <object> <top>)
576 @node Generic functions
577 @subsection Generic functions
580 * Generic functions and methods::
585 @node Generic functions and methods
586 @subsubsection Generic functions and methods
588 @c \label{gf-n-methods}
589 Neither @goops{} nor CLOS use the message mechanism for methods as most
590 Object Oriented language do. Instead, they use the notion of
591 @dfn{generic functions}. A generic function can be seen as a methods
592 ``tanker''. When the evaluator requested the application of a generic
593 function, all the methods of this generic function will be grabbed and
594 the most specific among them will be applied. We say that a method
595 @var{M} is @emph{more specific} than a method @var{M'} if the class of
596 its parameters are more specific than the @var{M'} ones. To be more
597 precise, when a generic function must be ``called'' the system will:
599 @cindex generic function
602 search among all the generic function those which are applicable
604 sort the list of applicable methods in the ``most specific'' order
606 call the most specific method of this list (i.e. the first method of
607 the sorted methods list).
610 The definition of a generic function is done with the
611 @code{define-generic} macro. Definition of a new method is done with the
612 @code{define-method} macro. Note that @code{define-method} automatically
613 defines the generic function if it has not been defined
614 before. Consequently, most of the time, the @code{define-generic} needs
616 @findex define-generic
617 @findex define-method
618 Consider the following definitions:
622 (define-method (G (a <integer>) b) 'integer)
623 (define-method (G (a <real>) b) 'real)
624 (define-method (G a b) 'top)
627 The @code{define-generic} call defines @var{G} as a generic
628 function. Note that the signature of the generic function is not given
629 upon definition, contrarily to CLOS. This will permit methods with
630 different signatures for a given generic function, as we shall see
631 later. The three next lines define methods for the @var{G} generic
632 function. Each method uses a sequence of @dfn{parameter specializers}
633 that specify when the given method is applicable. A specializer permits
634 to indicate the class a parameter must belong to (directly or
635 indirectly) to be applicable. If no specializer is given, the system
636 defaults it to @code{<top>}. Thus, the first method definition is
639 @cindex parameter specializers
641 (define-method (G (a <integer>) (b <top>)) 'integer)
644 Now, let us look at some possible calls to generic function @var{G}:
647 (G 2 3) @result{} integer
648 (G 2 #t) @result{} integer
649 (G 1.2 'a) @result{} real
650 @c (G #3 'a) @result{} real @c was {\sharpsign}
651 (G #t #f) @result{} top
652 (G 1 2 3) @result{} error (since no method exists for 3 parameters)
655 The preceding methods use only one specializer per parameter list. Of
656 course, each parameter can use a specializer. In this case, the
657 parameter list is scanned from left to right to determine the
658 applicability of a method. Suppose we declare now
661 (define-method (G (a <integer>) (b <number>)) 'integer-number)
662 (define-method (G (a <integer>) (b <real>)) 'integer-real)
663 (define-method (G (a <integer>) (b <integer>)) 'integer-integer)
664 (define-method (G a (b <number>)) 'top-number)
670 (G 1 2) @result{} integer-integer
671 (G 1 1.0) @result{} integer-real
672 (G 1 #t) @result{} integer
673 (G 'a 1) @result{} top-number
677 @subsubsection Next-method
679 When you call a generic function, with a particular set of arguments,
680 GOOPS builds a list of all the methods that are applicable to those
681 arguments and orders them by how closely the method definitions match
682 the actual argument types. It then calls the method at the top of this
683 list. If the selected method's code wants to call on to the next method
684 in this list, it can do so by using @code{next-method}.
687 (define-method (Test (a <integer>)) (cons 'integer (next-method)))
688 (define-method (Test (a <number>)) (cons 'number (next-method)))
689 (define-method (Test a) (list 'top))
692 With these definitions,
695 (Test 1) @result{} (integer number top)
696 (Test 1.0) @result{} (number top)
697 (Test #t) @result{} (top)
700 @code{next-method} is always called as just @code{(next-method)}. The
701 arguments for the next method call are always implicit, and always the
702 same as for the original method call.
704 If you want to call on to a method with the same name but with a
705 different set of arguments (as you might with overloaded methods in C++,
706 for example), you do not use @code{next-method}, but instead simply
707 write the new call as usual:
710 (define-method (Test (a <number>) min max)
711 (if (and (>= a min) (<= a max))
712 (display "Number is in range\n"))
722 (You should be careful in this case that the @code{Test} calls do not
723 lead to an infinite recursion, but this consideration is just the same
724 as in Scheme code in general.)
727 @subsubsection Example
729 In this section we shall continue to define operations on the @code{<my-complex>}
730 class defined in Figure@ 2. Suppose that we want to use it to implement
731 complex numbers completely. For instance a definition for the addition of
732 two complexes could be
735 (define-method (new-+ (a <my-complex>) (b <my-complex>))
736 (make-rectangular (+ (real-part a) (real-part b))
737 (+ (imag-part a) (imag-part b))))
740 To be sure that the @code{+} used in the method @code{new-+} is the standard
744 (define-generic new-+)
747 (define-method (new-+ (a <my-complex>) (b <my-complex>))
748 (make-rectangular (+ (real-part a) (real-part b))
749 (+ (imag-part a) (imag-part b)))))
752 The @code{define-generic} ensures here that @code{new-+} will be defined
753 in the global environment. Once this is done, we can add methods to the
754 generic function @code{new-+} which make a closure on the @code{+}
755 symbol. A complete writing of the @code{new-+} methods is shown in
761 (define-generic new-+)
765 (define-method (new-+ (a <real>) (b <real>)) (+ a b))
767 (define-method (new-+ (a <real>) (b <my-complex>))
768 (make-rectangular (+ a (real-part b)) (imag-part b)))
770 (define-method (new-+ (a <my-complex>) (b <real>))
771 (make-rectangular (+ (real-part a) b) (imag-part a)))
773 (define-method (new-+ (a <my-complex>) (b <my-complex>))
774 (make-rectangular (+ (real-part a) (real-part b))
775 (+ (imag-part a) (imag-part b))))
777 (define-method (new-+ (a <number>)) a)
779 (define-method (new-+) 0)
781 (define-method (new-+ . args)
783 (apply new-+ (cdr args)))))
788 @center @emph{Fig 3: Extending @code{+} for dealing with complex numbers}
793 We use here the fact that generic function are not obliged to have the
794 same number of parameters, contrarily to CLOS. The four first methods
795 implement the dyadic addition. The fifth method says that the addition
796 of a single element is this element itself. The sixth method says that
797 using the addition with no parameter always return 0. The last method
798 takes an arbitrary number of parameters@footnote{The parameter list for
799 a @code{define-method} follows the conventions used for Scheme
800 procedures. In particular it can use the dot notation or a symbol to
801 denote an arbitrary number of parameters}. This method acts as a kind
802 of @code{reduce}: it calls the dyadic addition on the @emph{car} of the
803 list and on the result of applying it on its rest. To finish, the
804 @code{set!} permits to redefine the @code{+} symbol to our extended
808 To terminate our implementation (integration?) of complex numbers, we can
809 redefine standard Scheme predicates in the following manner:
812 (define-method (complex? c <my-complex>) #t)
813 (define-method (complex? c) #f)
815 (define-method (number? n <number>) #t)
816 (define-method (number? n) #f)
821 Standard primitives in which complex numbers are involved could also be
822 redefined in the same manner.