exercise-2_4-complex-numbers.scm (2099B)
1 (define-library (2_4-complex-numbers) 2 (import (scheme base)) 3 4 (begin 5 (define (type-tag datum) 6 (if (and (pair? datum) 7 (symbol? (car datum))) 8 (car datum) 9 (error "Bad tagged datum: TYPE-TAG " datum))) 10 11 (define (contents datum) 12 (if (and (pair? datum) 13 (symbol? (car datum))) 14 (cdr datum) 15 (error "Bad tagged datum: CONTENTS " datum))) 16 17 (define (rectangular? z) 18 (eq? (type-tag z) 'rectangular)) 19 20 (define (polar? z) 21 (eq? (type-tag z) 'polar)) 22 23 ;; Ben representation 24 25 (define (real-part-rectangular z) (car z)) 26 (define (imag-part-rectangular z) (cdr z)) 27 28 (define (magnitude-rectangular z) 29 (sqrt (+ (square (real-part-rectangular z)) 30 (square (imag-part-rectangular z))))) 31 32 (define (angle-rectangular z) 33 (atan (imag-part-rectangular z) 34 (real-part-rectangular z))) 35 36 (define (make-from-real-imag-rectangular x y) 37 (attach-tag 'rectangular (cons x y))) 38 39 (define (make-from-mag-ang-rectangular r a) 40 (attach-tag 41 'rectangular 42 (cons (* r (cos a)) 43 (* r (sin a))))) 44 45 ;; Alyssa representation 46 47 (define (real-part-polar z) 48 (* (magnitude-poler z) 49 (cos (angle-polar z)))) 50 51 (define (imag-part-polar z) 52 (* (magnitude-poler z) 53 (sin (angle-polar z)))) 54 55 (define (magnitude-part-polar z) 56 (car z)) 57 58 (define (angle-part-polar z) 59 (cdr z)) 60 61 (define (make-from-real-imag real imag) 62 (list 'complex-real-imag real imag)) 63 64 (define (make-from-mag-ang mag ang) 65 (list 'comlex-mag-ang mag ang)) 66 67 (define (add-complex z1 z2) 68 (make-from-real-imag 69 (+ (real-part z1) (real-part z2)) 70 (+ (imag-part z1) (imag-part z2)))) 71 72 (define (mul-complex z1 z2) 73 (make-from-real-imag 74 (* (magnitude z1) (magnitude z2)) 75 (+ (angle z1) (angle z2)))) 76 77 (define (sub-complex z1 z2) 78 (make-from-real-imag 79 (/ (magnitude z1) (magnitude z2)) 80 (- (angle z1) (angle z2))))))