www.delorie.com/gnu/docs/guile/goops_73.html  search 
Buy GNU books!  
[ < ]  [ > ]  [ << ]  [ Up ]  [ >> ]  [Top]  [Contents]  [Index]  [ ? ] 
In this section we shall continue to define operations on the <complex>
class defined in Figure 2. Suppose that we want to use it to implement
complex numbers completely. For instance a definition for the addition of
two complexes could be
(definemethod (new+ (a <complex>) (b <complex>)) (makerectangular (+ (realpart a) (realpart b)) (+ (imagpart a) (imagpart b)))) 
To be sure that the +
used in the method new+
is the standard
addition we can do:
(definegeneric new+) (let ((+ +)) (definemethod (new+ (a <complex>) (b <complex>)) (makerectangular (+ (realpart a) (realpart b)) (+ (imagpart a) (imagpart b))))) 
The definegeneric
ensures here that new+
will be defined
in the global environment. Once this is done, we can add methods to the
generic function new+
which make a closure on the +
symbol. A complete writing of the new+
methods is shown in
Figure 3.
+ for dealing with complex numbers

We use here the fact that generic function are not obliged to have the
same number of parameters, contrarily to CLOS. The four first methods
implement the dyadic addition. The fifth method says that the addition
of a single element is this element itself. The sixth method says that
using the addition with no parameter always return 0. The last method
takes an arbitrary number of parameters(5). This method acts as a kind
of reduce
: it calls the dyadic addition on the car of the
list and on the result of applying it on its rest. To finish, the
set!
permits to redefine the +
symbol to our extended
addition.
To terminate our implementation (integration?) of complex numbers, we can redefine standard Scheme predicates in the following manner:
(definemethod (complex? c <complex>) #t) (definemethod (complex? c) #f) (definemethod (number? n <number>) #t) (definemethod (number? n) #f) ... ... 
Standard primitives in which complex numbers are involved could also be redefined in the same manner.
[ < ]  [ > ]  [ << ]  [ Up ]  [ >> ]  [Top]  [Contents]  [Index]  [ ? ] 
webmaster  delorie software privacy 
Copyright © 2003 by The Free Software Foundation  Updated Jun 2003 