Merge branch 'master' into wip-manual-2
[bpt/guile.git] / doc / ref / goops-tutorial.texi
1 @c -*-texinfo-*-
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.
6
7 @c Original attribution:
8
9 @c
10 @c STk Reference manual (Appendix: An Introduction to STklos)
11 @c
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
20 @c warranty.
21 @c
22
23 @c Adapted for use in Guile with the authors permission
24
25 @c @macro goops @c was {\stklos}
26 @c GOOPS
27 @c @end macro
28
29 @c @macro guile @c was {\stk}
30 @c Guile
31 @c @end macro
32
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{}.
36
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:
40
41 @lisp
42 (use-modules (oop goops))
43 @end lisp
44 @findex (oop goops)
45 @cindex main module
46 @cindex loading
47 @cindex preparing
48
49 @menu
50 * Copyright::
51 * Class definition::
52 * Instance creation and slot access::
53 * Slot description::
54 * Inheritance::
55 * Generic functions::
56 @end menu
57
58 @node Copyright
59 @subsection Copyright
60
61 Original attribution:
62
63 STk Reference manual (Appendix: An Introduction to STklos)
64
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
73 warranty.
74
75 Adapted for use in Guile with the author's permission
76
77 @node Class definition
78 @subsection Class definition
79
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}:
82
83 @findex define-class
84 @cindex class
85 @lisp
86 (define-class @var{class} (@var{superclass} @dots{})
87 @var{slot-description} @dots{}
88 @var{class-option} @dots{})
89 @end lisp
90
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}.
98 @cindex slot
99
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:
105
106 @lisp
107 (define-class <my-complex> (<number>)
108 r i)
109 @end lisp
110
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
118 @code{<integer>}.}
119
120 @node Instance creation and slot access
121 @subsection Instance creation and slot access
122
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
129
130 @findex make
131 @cindex instance
132 @lisp
133 (define c (make <my-complex>))
134 @end lisp
135
136 @noindent
137 will create a new @code{<my-complex>} object and will bind it to the @code{c}
138 Scheme variable.
139
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.
143
144 @findex slot-set!
145 @findex slot-ref
146 @lisp
147 @group
148 (slot-set! c 'r 10)
149 (slot-set! c 'i 3)
150 (slot-ref c 'r) @result{} 10
151 (slot-ref c 'i) @result{} 3
152 @end group
153 @end lisp
154
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.
158
159 First load the module @code{(oop goops describe)}:
160
161 @example
162 @code{(use-modules (oop goops describe))}
163 @end example
164
165 @noindent
166 Then the expression
167
168 @lisp
169 (describe c)
170 @end lisp
171
172 @noindent
173 will print the following information on the standard output:
174
175 @smalllisp
176 #<<my-complex> 401d8638> is an instance of class <my-complex>
177 Slots are:
178 r = 10
179 i = 3
180 @end smalllisp
181
182 @node Slot description
183 @subsection Slot description
184 @c \label{slot-description}
185
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
189 given below:
190
191 @cindex keyword
192 @itemize @bullet
193 @item
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
198 @findex #:init-value
199
200 @item
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
206 @findex #:init-form
207
208 @item
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
213 @findex #:init-thunk
214
215 @item
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
222
223 @item
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.
227 @findex #:getter
228 @cindex top level environment
229 @cindex getter
230
231 @item
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.
235 @findex #:setter
236 @cindex top level environment
237 @cindex setter
238
239 @item
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!}.
245 @findex set!
246 @findex #:accessor
247 @cindex top level environment
248 @cindex accessor
249
250 @item
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:
254
255 @itemize @minus
256 @item
257 @code{#:instance} indicates that each instance gets its own storage for
258 the slot. This is the default.
259 @item
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.
264 @item
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
268 value.
269 @item
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.
274 @findex #:slot-set!
275 @findex #:slot-ref
276 @findex #:virtual
277 @findex #:class
278 @findex #:each-subclass
279 @findex #:instance
280 @findex #:allocation
281 @end itemize
282 @end itemize
283
284 To illustrate slot description, we shall redefine the @code{<my-complex>} class
285 seen before. A definition could be:
286
287 @lisp
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))
291 @end lisp
292
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.
299
300 @lisp
301 (define c1 (make <my-complex> #:r 1 #:i 2))
302 (get-r c1) @result{} 1
303 (set-r! c1 12)
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
308 @end lisp
309
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:
315
316 @findex set!
317 @lisp
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))
321 @end lisp
322
323 Using this class definition, reading the real part of the @code{c}
324 complex can be done with:
325 @lisp
326 (real-part c)
327 @end lisp
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!}.
330 @lisp
331 (set! (real-part c) new-value)
332 @end lisp
333
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
340 given in Figure@ 2.
341
342 @example
343 @group
344 @lisp
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)))))))
367
368 @end lisp
369 @center @emph{Fig 2: A @code{<my-complex>} number class definition using virtual slots}
370 @end group
371 @end example
372
373 @sp 3
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
380 expression
381
382 @findex #:slot-set!
383 @findex #:slot-ref
384 @lisp
385 (slot-set! c 'a 3)
386 @end lisp
387
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
390
391 @lisp
392 ((lambda o m)
393 (let ((m (slot-ref o 'm)))
394 (slot-set! o 'r (* m (cos a)))
395 (slot-set! o 'i (* m (sin a))))
396 c 3)
397 @end lisp
398
399 A more complete example is given below:
400
401 @example
402 @group
403 @smalllisp
404 (define c (make <my-complex> #:r 12 #:i 20))
405 (real-part c) @result{} 12
406 (angle c) @result{} 1.03037682652431
407 (slot-set! c 'i 10)
408 (set! (real-part c) 1)
409 (describe c)
410 @print{}
411 #<<my-complex> 401e9b58> is an instance of class <my-complex>
412 Slots are:
413 r = 1
414 i = 10
415 m = 10.0498756211209
416 a = 1.47112767430373
417 @end smalllisp
418 @end group
419 @end example
420
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
423 Scheme primitives.
424
425 @lisp
426 (define make-rectangular
427 (lambda (x y) (make <my-complex> #:r x #:i y)))
428
429 (define make-polar
430 (lambda (x y) (make <my-complex> #:magn x #:angle y)))
431 @end lisp
432
433 @node Inheritance
434 @subsection Inheritance
435 @c \label{inheritance}
436
437 @menu
438 * Class hierarchy and inheritance of slots::
439 * Class precedence list::
440 @end menu
441
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
446 class definitions:
447
448 @lisp
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)
455 @end lisp
456
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.
466
467 @example
468 @group
469 @iftex
470 @center @image{hierarchy,5in}
471 @end iftex
472 @ifnottex
473 @verbatiminclude hierarchy.txt
474 @end ifnottex
475
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
479 figure.)}
480 @end group
481 @end example
482
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,
488
489 @lisp
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))
494 @end lisp
495
496 @emph{Note: } The order of slots is not significant.
497
498 @node Class precedence list
499 @subsubsection Class precedence list
500
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
505 rule:
506
507 @display
508 @cartouche
509 Rule 1: Each class is more specific than its superclasses.@c was \bf
510 @end cartouche
511 @end display
512
513 With multiple inheritance, ordering is harder. Suppose we have
514
515 @lisp
516 (define-class X ()
517 (x #:init-value 1))
518
519 (define-class Y ()
520 (x #:init-value 2))
521
522 (define-class Z (X Y)
523 (@dots{}))
524 @end lisp
525
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.
531 So:
532
533 @display
534 @cartouche
535 Rule 2: For a given class, superclasses listed earlier are more
536 specific than those listed later.
537 @end cartouche
538 @end display
539
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}.
546
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
550
551 @example
552 (f d e a c b <object> <top>)
553 @end example
554
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.
558
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,
562
563 @lisp
564 (class-precedence-list B) @result{} (#<<class> B 401b97c8>
565 #<<class> <object> 401e4a10>
566 #<<class> <top> 4026a9d8>)
567 @end lisp
568
569 However, this result is not too much readable; using the function
570 @code{class-name} yields a clearer result:
571
572 @lisp
573 (map class-name (class-precedence-list B)) @result{} (B <object> <top>)
574 @end lisp
575
576 @node Generic functions
577 @subsection Generic functions
578
579 @menu
580 * Generic functions and methods::
581 * Next-method::
582 * Example::
583 @end menu
584
585 @node Generic functions and methods
586 @subsubsection Generic functions and methods
587
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:
598
599 @cindex generic function
600 @enumerate
601 @item
602 search among all the generic function those which are applicable
603 @item
604 sort the list of applicable methods in the ``most specific'' order
605 @item
606 call the most specific method of this list (i.e. the first method of
607 the sorted methods list).
608 @end enumerate
609
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
615 not be used.
616 @findex define-generic
617 @findex define-method
618 Consider the following definitions:
619
620 @lisp
621 (define-generic G)
622 (define-method (G (a <integer>) b) 'integer)
623 (define-method (G (a <real>) b) 'real)
624 (define-method (G a b) 'top)
625 @end lisp
626
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
637 equivalent to
638
639 @cindex parameter specializers
640 @lisp
641 (define-method (G (a <integer>) (b <top>)) 'integer)
642 @end lisp
643
644 Now, let us look at some possible calls to generic function @var{G}:
645
646 @lisp
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)
653 @end lisp
654
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
659
660 @lisp
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)
665 @end lisp
666
667 In this case,
668
669 @lisp
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
674 @end lisp
675
676 @node Next-method
677 @subsubsection Next-method
678
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}.
685
686 @lisp
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))
690 @end lisp
691
692 With these definitions,
693
694 @lisp
695 (Test 1) @result{} (integer number top)
696 (Test 1.0) @result{} (number top)
697 (Test #t) @result{} (top)
698 @end lisp
699
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.
703
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:
708
709 @lisp
710 (define-method (Test (a <number>) min max)
711 (if (and (>= a min) (<= a max))
712 (display "Number is in range\n"))
713 (Test a))
714
715 (Test 2 1 10)
716 @print{}
717 Number is in range
718 @result{}
719 (integer number top)
720 @end lisp
721
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.)
725
726 @node Example
727 @subsubsection Example
728
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
733
734 @lisp
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))))
738 @end lisp
739
740 To be sure that the @code{+} used in the method @code{new-+} is the standard
741 addition we can do:
742
743 @lisp
744 (define-generic new-+)
745
746 (let ((+ +))
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)))))
750 @end lisp
751
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
756 Figure@ 3.
757
758 @example
759 @group
760 @lisp
761 (define-generic new-+)
762
763 (let ((+ +))
764
765 (define-method (new-+ (a <real>) (b <real>)) (+ a b))
766
767 (define-method (new-+ (a <real>) (b <my-complex>))
768 (make-rectangular (+ a (real-part b)) (imag-part b)))
769
770 (define-method (new-+ (a <my-complex>) (b <real>))
771 (make-rectangular (+ (real-part a) b) (imag-part a)))
772
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))))
776
777 (define-method (new-+ (a <number>)) a)
778
779 (define-method (new-+) 0)
780
781 (define-method (new-+ . args)
782 (new-+ (car args)
783 (apply new-+ (cdr args)))))
784
785 (set! + new-+)
786 @end lisp
787
788 @center @emph{Fig 3: Extending @code{+} for dealing with complex numbers}
789 @end group
790 @end example
791
792 @sp 3
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
805 addition.
806
807 @sp 3
808 To terminate our implementation (integration?) of complex numbers, we can
809 redefine standard Scheme predicates in the following manner:
810
811 @lisp
812 (define-method (complex? c <my-complex>) #t)
813 (define-method (complex? c) #f)
814
815 (define-method (number? n <number>) #t)
816 (define-method (number? n) #f)
817 @dots{}
818 @dots{}
819 @end lisp
820
821 Standard primitives in which complex numbers are involved could also be
822 redefined in the same manner.
823