rectangular.scm 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. (define-module (rectangular)
  2. #:use-module (rnrs base)
  3. #:use-module ((guile) #:select (lambda* λ simple-format))
  4. #:use-module (tagged-data)
  5. #:use-module (math)
  6. #:export (make-from-real-imag
  7. make-from-mag-ang
  8. rectangular?
  9. data-tag
  10. real-part
  11. imag-part
  12. magnitude
  13. angle
  14. install-package))
  15. ;;; IMPROVEMENT: Instead of renaming all procedures to have a prefix
  16. ;;; or suffix or some other means of telling what implementation they
  17. ;;; are from, we put them in a separate module and distinguish them
  18. ;;; upon importing them. This way neither one of the
  19. ;;; implementors/coders need to care about name collisions.
  20. ;;; NOTE: A module system is not yet introduced yet in the book at the
  21. ;;; point of this exercise.
  22. ;; representation in rectangular form
  23. ;; z = x + iy, i^2 = -1 -> point in a plane, real: x, imaginary: y
  24. (define data-tag 'rectangular)
  25. ;;; Constructors.
  26. (define make-from-real-imag
  27. (λ (real imag)
  28. (attach-tag data-tag
  29. (cons real imag))))
  30. (define make-from-mag-ang
  31. (λ (mag ang)
  32. (attach-tag data-tag
  33. (cons (* mag (cos ang))
  34. (* mag (sin ang))))))
  35. ;;; Accessors.
  36. (define real-part
  37. (λ (num)
  38. (simple-format #t "real-part in rectangular num: ~a" num)
  39. (car num)))
  40. (define imag-part
  41. (λ (num)
  42. (cdr num)))
  43. (define magnitude
  44. (λ (num)
  45. (sqrt (+ (square (real-part num))
  46. (square (imag-part num))))))
  47. (define angle
  48. (λ (num)
  49. (atan (imag-part num)
  50. (real-part num))))
  51. (define rectangular?
  52. (λ (datum)
  53. (eq? (type-tag datum) data-tag)))
  54. (define install-package
  55. (λ (lookup-table put)
  56. (let iter
  57. ([funcs° (list make-from-real-imag
  58. make-from-mag-ang
  59. rectangular?
  60. data-tag
  61. real-part
  62. imag-part
  63. magnitude
  64. angle)])
  65. (cond
  66. [(null? funcs°) lookup-table]
  67. [else
  68. (put lookup-table op type func)
  69. (iter (cdr funcs°))]))))