SICP 2.4 exercises cont. 3


(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)
           (error "Unknown op -- MAKE-FROM-MAG-ANG" op))))

(define (apply-generic op arg) (arg op))

Easy enough, but implementing this gave a much clearer idea of what the book meant by message passing.


Generic operations with explicit dispatch
New Type – For each operation, create procedures that deal with the new type. For each generic operation, add a conditional statement that tests if the tag corresponds to the new type and calls the correct procedure that was just defined.
New Operation – For each type, create a procedure that deals with the new operation. Create a new generic operation that deals with each type currently in the system correctly using conditional statements.

Data Directed Style
New Type – Create procedures for the new type for each operation and put them into the table indexed by the procedure name and the type name.
New Operation – Create procedures for the new operation for each type and put them into the table indexed by the procedure name and type name.

Message Passing Style
New Type – Create a new procedure/data object which deals with existing operations through conditional statements and returns a correct procedure representing the type.
New Operation – For each data object defined, create a new conditional statement that handles the new operation.

Message passing is most appropriate when new types are added frequently, because it only requires defining one new procedure.

Data Directed is most appropriate for when new operations are added frequently as new values can be placed into the table as needed.

Finally finished section 2,4! This took much longer than expected thanks to the start of school and all the obligations that came with it. Still, my time management can be improved. Hopefully I can work through the book more consistently from now on.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s