7 (define (add-complex z1 z2)
8 (make-from-real-imag (+ (real-part z1) (real-part z2))
9 (+ (imag-part z1) (imag-part z2))))
11 (define (sub-complex z1 z2)
12 (make-from-real-imag (- (real-part z1) (real-part z2))
13 (- (imag-part z1) (imag-part z2))))
15 (define (mul-complex z1 z2)
16 (make-from-mag-ang (* (magnitude z1) (magnitude z2))
17 (+ (angle z1) (angle z2))))
19 (define (div-complex z1 z2)
20 (make-from-mag-ang (/ (magnitude z1) (magnitude z2))
21 (- (angle z1) (angle z2))))
23 ;;; constructors and selectors for rectangular form
24 (define (real-part-rect z) (car z))
25 (define (imag-part-rect z) (cdr z))
27 (define (magnitude-rect z)
28 (sqrt (+ (square (real-part-rect z))
29 (square (imag-part-rect z)))))
31 (define (angle-rect z)
32 (atan (imag-part-rect z) (real-part-rect z)))
34 (define (make-from-real-imag-rect x y) (attach-tag 'rectangular (cons x y)))
36 (define (make-from-mag-ang-rect r a)
37 (attach-tag 'rectangular (cons (* r (cos a)) (* r (sin a)))))
39 ;;; constructors and selectors for polar form
40 (define (real-part-polar z) (* (magnitude-polar z)
41 (cos (angle-polar z))))
43 (define (imag-part-polar z) (* (magnitude-polar z)
44 (sin (angle-polar z))))
46 (define (magnitude-polar z) (car z))
47 (define (angle-polar z) (cdr z))
49 (define (make-from-real-imag x y)
51 (cons (sqrt (+ (square x) (square y)))
54 (define (make-from-mag-ang r a) (attach-tag 'polar (cons r a)))
57 (define (attach-tag type-tag contents)
58 (cons type-tag contents))
60 (define (type-tag datum)
63 (error "Bad tagged datum -- TYPE-TAG" datum)))
65 (define (contents datum)
68 (error "Bad tagged datum -- CONTENTS" datum)))
70 (define (rectangular? z)
71 (eq? (type-tag z) 'rectangular))
74 (eq? (type-tag z) 'polar))
79 [(rectangular? z) (real-part-rect (contents z))]
80 [(polar? z) (real-part-polar (contents z))]
81 [else (error "unknown type -- real-part" z)]))
85 [(rectangular? z) (imag-part-rect (contents z))]
86 [(polar? z) (imag-part-rect (contents z))]
87 [else (error "unknown type -- imag part" z)]))
91 [(rectangular? z) (magnitude-rect (contents z))]
92 [(polar? z) (magnitude-polar (contents z))]
93 [else (error "Unknown type -- MAGNITUDE" z)]))
96 (cond [(rectangular? z) (angle-rect (contents z))]
97 [(polar? z) (angle-polar (contents z))]
98 [else (error "Unknown type -- ANGLE" z)]))
100 (define (make-from-real-imag x y)
101 (make-from-real-imag-rect x y))
103 (define (make-from-mag-ang r a)
104 (make-from-mag-ang-polar r a))
107 (define (make-from-real-imag x y)
108 (define (dispatch op)
110 [(eq? op 'real-part) x]
111 [(eq? op 'imag-part) y]
113 (sqrt (+ (square x) (square y)))]
114 [(eq? op 'angle) (atan y x)]
116 (error "unknown op" op)]))