Blob


1 (define (make-from-real-imag x y)
2 (define (dispatch op)
3 (cond ((eq? op 'real-part) x)
4 ((eq? op 'imag-part) y)
5 ((eq? op 'magnitude)
6 (sqrt (+ (square x) (square y))))
7 ((eq? op 'angle) (atan y x))
8 (else (error "Unknown op -- MAKE-FROM-REAL-IMAG" op))))
9 dispatch)
11 (define (apply-generic op arg) (arg op))
13 ;; 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.
15 (define (make-from-mag-ang r a)
16 (define (dispatch op)
17 (cond ((eq? op 'real-part) (* r (cos a)))
18 ((eq? op 'imag-part) (* r (sin a)))
19 ((eq? op 'magnitude) r)
20 ((eq? op 'angle) a)
21 (else (error "Unknown op -- MAKE-FROM-REAL-IMAG" op))))
22 dispatch)
24 ;; 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?
26 ;; For generic operations with explicit dispatch, you need to update every single one of the generic selectors each time you add a new data type. You'll also need to add a new constructor for that data type. If you add a new generic operation, all of the data types that want to support it will need to provide a procedure. The maintainer of the generic operation needs to know about all the data types in order to make a proper dispatch. Explicit dispatch is the most burdensome to maintain.
28 ;; For data-directed and message-passing style, each time you add a new data type, there is no need for the generic operation to be updated. For data-directed style, the implementor of the new data type just needs to put the corresponding procedure into the table. For message-passing style, a table does not even need to be updated. The implementor only needs to update his data object to learn how to handle any messages the object needs to support.
30 ;; When adding a new operation, for both cases, the implementor of the data type will need to add a new procedure (or learn how to respond to the new operation message) if the operation needs to be supported.