計算機程序的構造和解釋 練習題2.75

#lang racket
(define (square x) (* x x))
(define pi 3.1415926535897932384626433832795)
(define (make-from-real-imag x y)
  (define (dispatch op)
    (cond ((eq? op 'real-part) x)
          ((eq? op 'imag-part) y)
          ((eq? op 'magnitude)
           (sqrt (+ (square x) (square y))))
          ((eq? op 'angle) (atan y x))
          (else
           (error "Unknown op -- MAKE-FROM-REAL-IMAG" op))))
  dispatch)
(define (make-from-mag-ang r a)
   (define (dispatch op)
    (cond ((eq? op 'real-part) (* r (cos a)))
          ((eq? op 'imag-part) (* r (sin a)))
          ((eq? op 'magnitude) r)
          ((eq? op 'angle) a)
          (else
           (error "Unknown op -- MAKE-FROM-MAG-ANG" op))))
  dispatch)
(define (apply-generic op arg) (arg op))
(define real-imag (make-from-real-imag 1 2))
(define mag-ang (make-from-mag-ang 1 (/ pi 6)))
(define (real-part z)
  (apply-generic 'real-part z))
(define (imag-part z)
   (apply-generic 'imag-part z))
(define (magnitude z)
   (apply-generic 'magnitude z))
(define (angle z)
   (apply-generic 'angle z))
(real-part real-imag)
(imag-part real-imag)
(magnitude real-imag)
(angle real-imag)
(real-part mag-ang)
(imag-part mag-ang)
(magnitude mag-ang)
(angle mag-ang)


運行結果

1
2
2.23606797749979
1.1071487177940904
0.8660254037844387
0.49999999999999994
1
0.5235987755982988
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章