Monday, January 12, 2009

SICP Section 2.4 Multiple Representations for Abstract Data

Exercise 2.75. Implement the constructor make-from-mag-ang in message-passing style. This procedure should be analogous to the make-from-real-imag procedure given above.

Answer:
  1. (define (make-from-mag-ang r a)  
  2.   (define (dispatch op)  
  3.     (cond ((eq? op 'real-part)  
  4.            (* r (cos a)))  
  5.           ((eq? op 'imag-part)  
  6.            (* r (sin a)))  
  7.           ((eq? op 'magnitude)  
  8.            r)  
  9.           ((eq? op 'angle)  
  10.            a)  
  11.           (else  
  12.            (error "Unknown op -- MAKE-FROM-MAG-ANG" op))))            
  13.   dispatch)  

Exercise 2.76. As a large system with generic operations evolves, new types of data objects or new operations may be needed. For each of the three strategies -- generic operations with explicit dispatch, data-directed style, and message-passing-style -- describe the changes that must be made to a system in order to add new types or new operations. Which organization would be most appropriate for a system in which new types must often be added? Which would be most appropriate for a system in which new operations must often be added?

Answer:
  • Generic operations with explicit dispatch: explicit dispatch is relatively easier to code. However adding new types would require that all existing functions be changed appropriately. For this reason makes explicit dispatch is less suited for a system in which new types must often be added
  • Data-directed style: adding new types would not require extensive changes at the top level. However new packages would need to be added behind the scenes to facilitate operation.
  • Message-passing-style: this requires the addition of a suitable type of procedure/object which can accept the messages as necessary. The top level does not need to change.


No comments: