]> git.donarmstrong.com Git - lilypond.git/blob - guile18/doc/goops/goops-tutorial.texi
Import guile-1.8 as multiple upstream tarball component
[lilypond.git] / guile18 / doc / goops / goops-tutorial.texi
1 @c Original attribution:
2
3 @c
4 @c STk Reference manual (Appendix: An Introduction to STklos)
5 @c
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
14 @c warranty.
15 @c
16
17 @c Adapted for use in Guile with the authors permission
18
19 @c @macro goops                    @c was {\stklos}
20 @c GOOPS
21 @c @end macro
22
23 @c @macro guile                    @c was {\stk}
24 @c Guile
25 @c @end macro
26
27 This is chapter was originally written by Erick Gallesio as an appendix
28 for the STk reference manual, and subsequently adapted to @goops{}.
29
30 @menu
31 * Copyright::
32 * Intro::                
33 * Class definition and instantiation::  
34 * Inheritance::                 
35 * Generic functions::           
36 @end menu
37
38 @node Copyright, Intro, Tutorial, Tutorial
39 @section Copyright
40
41 Original attribution:
42
43 STk Reference manual (Appendix: An Introduction to STklos)
44
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
53 warranty.
54
55 Adapted for use in Guile with the authors permission
56
57 @node Intro, Class definition and instantiation, Copyright, Tutorial
58 @section Introduction
59
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
64 the Scheme language.
65
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}).
71
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{}).
75
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:
79
80 @lisp
81 (use-modules (oop goops))
82 @end lisp
83 @findex (oop goops)
84 @cindex main module
85 @cindex loading
86 @cindex preparing
87
88 @node Class definition and instantiation, Inheritance, Intro, Tutorial
89 @section Class definition and instantiation
90
91 @menu
92 * Class definition::            
93 @end menu
94
95 @node Class definition,  , Class definition and instantiation, Class definition and instantiation
96 @subsection Class definition
97
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}:
101
102 @findex define-class
103 @cindex class
104 @lisp
105 (define-class @var{class} (@var{superclass} @dots{})
106    @var{slot-description} @dots{}
107    @var{class-option} @dots{})
108 @end lisp
109
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}.
117 @cindex slot
118
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
121 class definition:
122
123 @lisp
124 (define-class  <complex> (<number>)
125    r i)
126 @end lisp
127
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}.
144
145 @node Inheritance, Generic functions, Class definition and instantiation, Tutorial
146 @section Inheritance
147 @c \label{inheritance}
148
149 @menu
150 * Class hierarchy and inheritance of slots::  
151 * Instance creation and slot access::  
152 * Slot description::            
153 * Class precedence list::       
154 @end menu
155
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
160 class definitions:
161
162 @lisp
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)
169 @end lisp
170
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.
180
181 @example
182 @group
183 @image{hierarchy}
184 @center @emph{Fig 1: A class hierarchy}
185 @iftex
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
188 figure.)}
189 @end iftex
190 @end group
191 @end example
192
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,
198
199 @lisp
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))
204 @end lisp
205
206 @emph{Note: } The order of slots is not significant.
207
208 @node Instance creation and slot access, Slot description, Class hierarchy and inheritance of slots, Inheritance
209 @subsection Instance creation and slot access
210
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
217
218 @findex make
219 @cindex instance
220 @lisp
221 (define c (make <complex>))
222 @end lisp
223
224 will create a new @code{<complex>} object and will bind it to the @code{c}
225 Scheme variable.
226
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.
231
232 @findex slot-set!
233 @findex slot-ref
234 @lisp
235 @group
236 (slot-set! c 'r 10)
237 (slot-set! c 'i 3)
238 (slot-ref c 'r) @result{} 10
239 (slot-ref c 'i) @result{} 3
240 @end group
241 @end lisp
242
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.
246
247 First load the module @code{(oop goops describe)}:
248
249 @example
250 @code{(use-modules (oop goops describe))}
251 @end example
252
253 The expression
254
255 @smalllisp
256 (describe c)
257 @end smalllisp
258
259 will now print the following information on the standard output:
260
261 @lisp
262 #<<complex> 401d8638> is an instance of class <complex>
263 Slots are: 
264      r = 10
265      i = 3
266 @end lisp
267
268 @node Slot description, Class precedence list, Instance creation and slot access, Inheritance
269 @subsection Slot description
270 @c \label{slot-description}
271
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:
275
276 @cindex keyword
277 @itemize @bullet
278 @item
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
283 @findex #:init-value
284 @cindex top level environment
285
286 @item
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
292 @findex #:init-thunk
293 @cindex top level environment
294
295 @item
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
302
303 @item
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.
307 @findex #:getter
308 @cindex top level environment
309 @cindex getter
310
311 @item
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.
315 @findex #:setter
316 @cindex top level environment
317 @cindex setter
318
319 @item
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!}.
325 @findex set!
326 @findex #:accessor
327 @cindex top level environment
328 @cindex accessor
329
330 @item
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:
334
335 @itemize @minus
336 @item
337 @code{#:instance} indicates that each instance gets its own storage for
338 the slot. This is the default.
339 @item
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.
344 @item
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
348 value.
349 @item
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.
354 @findex #:slot-set!
355 @findex #:slot-ref
356 @findex #:virtual
357 @findex #:class
358 @findex #:each-subclass
359 @findex #:instance
360 @findex #:allocation
361 @end itemize
362 @end itemize
363
364 To illustrate slot description, we shall redefine the @code{<complex>} class 
365 seen before. A definition could be:
366
367 @lisp
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))
371 @end lisp
372
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.
379
380 @lisp
381 (define c1 (make <complex> #:r 1 #:i 2))
382 (get-r c1) @result{} 1
383 (set-r! c1 12)
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
388 @end lisp
389
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:
395
396 @findex set!
397 @lisp
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))
401 @end lisp
402
403 Using this class definition, reading the real part of the @code{c}
404 complex can be done with:
405 @lisp
406 (real-part c)
407 @end lisp
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!}.
410 @lisp
411 (set! (real-part c) new-value)
412 @end lisp
413
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
420 given in Figure@ 2.
421
422 @example
423 @group
424 @lisp
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)))))))
447
448 @end lisp
449 @center @emph{Fig 2: A @code{<complex>} number class definition using virtual slots}
450 @end group
451 @end example
452
453 @sp 3
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
460 expression
461
462 @findex #:slot-set!
463 @findex #:slot-ref
464 @lisp
465 (slot-set! c 'a 3)
466 @end lisp
467
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
470
471 @lisp
472 ((lambda o m)
473     (let ((m (slot-ref o 'm)))
474        (slot-set! o 'r (* m (cos a)))
475        (slot-set! o 'i (* m (sin a))))
476   c 3)
477 @end lisp
478
479 A more complete example is given below:
480
481 @example
482 @group
483 @lisp
484 (define c (make <complex> #:r 12 #:i 20))
485 (real-part c) @result{} 12
486 (angle c) @result{} 1.03037682652431
487 (slot-set! c 'i 10)
488 (set! (real-part c) 1)
489 (describe c) @result{}
490           #<<complex> 401e9b58> is an instance of class <complex>
491           Slots are: 
492                r = 1
493                i = 10
494                m = 10.0498756211209
495                a = 1.47112767430373
496 @end lisp
497 @end group
498 @end example
499
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
502 Scheme primitives.
503
504 @lisp
505 (define make-rectangular 
506    (lambda (x y) (make <complex> #:r x #:i y)))
507
508 (define make-polar
509    (lambda (x y) (make <complex> #:magn x #:angle y)))
510 @end lisp
511
512 @node Class precedence list,  , Slot description, Inheritance
513 @subsection Class precedence list
514
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
519 rule:
520
521 @display
522 @cartouche
523 Rule 1: Each class is more specific than its superclasses.@c was \bf
524 @end cartouche
525 @end display
526
527 With multiple inheritance, ordering is harder. Suppose we have
528
529 @lisp
530 (define-class X ()
531    (x #:init-value 1))
532
533 (define-class Y ()
534    (x #:init-value 2))
535
536 (define-class Z (X Y)
537    (@dots{}))
538 @end lisp
539
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.
545 So:
546
547 @display
548 @cartouche
549 Rule 2: For a given class, superclasses listed earlier are more
550         specific than those listed later.
551 @end cartouche
552 @end display
553
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}.
560
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
564
565 @example
566 (f d e a c b <object> <top>)
567 @end example
568
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.
572
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,
576
577 @lisp
578 (class-precedence-list B) @result{} (#<<class> B 401b97c8> 
579                                      #<<class> <object> 401e4a10> 
580                                      #<<class> <top> 4026a9d8>)
581 @end lisp
582
583 However, this result is not too much readable; using the function
584 @code{class-name} yields a clearer result:
585
586 @lisp
587 (map class-name (class-precedence-list B)) @result{} (B <object> <top>) 
588 @end lisp
589
590 @node Generic functions,  , Inheritance, Tutorial
591 @section Generic functions
592
593 @menu
594 * Generic functions and methods::  
595 * Next-method::                 
596 * Example::                     
597 @end menu
598
599 @node Generic functions and methods, Next-method, Generic functions, Generic functions
600 @subsection Generic functions and methods
601
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:
612
613 @cindex generic function
614 @enumerate
615 @item
616 search among all the generic function those which are applicable
617 @item
618 sort the list of applicable methods in the ``most specific'' order
619 @item
620 call the most specific method of this list (i.e. the first method of 
621 the sorted methods list).
622 @end enumerate
623
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
629 not be used.
630 @findex define-generic
631 @findex define-method
632 Consider the following definitions:
633
634 @lisp
635 (define-generic G)
636 (define-method  (G (a <integer>) b) 'integer)
637 (define-method  (G (a <real>) b) 'real)
638 (define-method  (G a b) 'top)
639 @end lisp
640
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
651 equivalent to
652
653 @cindex parameter specializers
654 @lisp
655 (define-method (G (a <integer>) (b <top>)) 'integer)
656 @end lisp
657
658 Now, let us look at some possible calls to generic function @var{G}:
659
660 @lisp
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)
667 @end lisp
668
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
673
674 @lisp
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)
679 @end lisp
680
681 In this case,
682
683 @lisp
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
688 @end lisp
689
690 @node Next-method, Example, Generic functions and methods, Generic functions
691 @subsection Next-method
692
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}.
699
700 @lisp
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))
704 @end lisp
705
706 With these definitions,
707
708 @lisp
709 (Test 1)   @result{} (integer number top)
710 (Test 1.0) @result{} (number top)
711 (Test #t)  @result{} (top)
712 @end lisp
713
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.
717
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:
722
723 @lisp
724 (define-method (Test (a <number>) min max)
725   (if (and (>= a min) (<= a max))
726       (display "Number is in range\n"))
727   (Test a))
728
729 (Test 2 1 10)
730 @print{}
731 Number is in range
732 @result{}
733 (integer number top)
734 @end lisp
735
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.)
739
740 @node Example,  , Next-method, Generic functions
741 @subsection Example
742
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
747
748 @lisp
749 (define-method (new-+ (a <complex>) (b <complex>))
750   (make-rectangular (+ (real-part a) (real-part b))
751                     (+ (imag-part a) (imag-part b))))
752 @end lisp
753
754 To be sure that the @code{+} used in the method @code{new-+} is the standard
755 addition we can do:
756
757 @lisp
758 (define-generic new-+)
759
760 (let ((+ +))
761   (define-method (new-+ (a <complex>) (b <complex>))
762     (make-rectangular (+ (real-part a) (real-part b))
763                       (+ (imag-part a) (imag-part b)))))
764 @end lisp
765
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
770 Figure@ 3.
771
772 @example
773 @group
774 @lisp
775 (define-generic new-+)
776
777 (let ((+ +))
778
779   (define-method (new-+ (a <real>) (b <real>)) (+ a b))
780
781   (define-method (new-+ (a <real>) (b <complex>)) 
782     (make-rectangular (+ a (real-part b)) (imag-part b)))
783
784   (define-method (new-+ (a <complex>) (b <real>))
785     (make-rectangular (+ (real-part a) b) (imag-part a)))
786
787   (define-method (new-+ (a <complex>) (b <complex>))
788     (make-rectangular (+ (real-part a) (real-part b))
789                       (+ (imag-part a) (imag-part b))))
790
791   (define-method (new-+ (a <number>))  a)
792   
793   (define-method (new-+) 0)
794
795   (define-method (new-+ . args)
796     (new-+ (car args) 
797       (apply new-+ (cdr args)))))
798
799 (set! + new-+)
800 @end lisp
801
802 @center @emph{Fig 3: Extending @code{+} for dealing with complex numbers}
803 @end group
804 @end example
805
806 @sp 3
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
819 addition.
820
821 @sp 3
822 To terminate our implementation (integration?) of  complex numbers, we can 
823 redefine standard Scheme predicates in the following manner:
824
825 @lisp
826 (define-method (complex? c <complex>) #t)
827 (define-method (complex? c)           #f)
828
829 (define-method (number? n <number>) #t)
830 (define-method (number? n)          #f)
831 @dots{}
832 @dots{}
833 @end lisp
834
835 Standard primitives in which complex numbers are involved could also be
836 redefined in the same manner.
837