Entropic Thoughts
16 hours ago
- The article demonstrates how to support multiple representations of complex numbers (rectangular and polar) using tagged data, inspired by SICP section 2.4.2.
- Initial implementation mimics Lisp with dynamic typing using cons cells, attach_tag, type_tag, and contents functions.
- Constructor functions make_rectangular and make_polar create tagged pairs, and extraction functions use trigonometry for conversions.
- Generic functions (real_part, imag_part, magnitude, angle) dispatch on the tag to handle both representations.
- The code is then refined by replacing dynamic typing with Haskell's static type system: using tuples, pattern matching, and Double values.
- Finally, a native algebraic data type (Complex) is introduced, eliminating custom tagging and reducing code from 80 lines to 30 lines.
- The article notes that this approach is not ideal and hints at data-directed programming as an alternative.