# SICP 2.5 exercises

2.77

When the user calls one of the procedures, such as (magnitude z), apply-generic is invoked and discovers the ‘(complex) tag. It looks in the table and discovers that the magnitude procedure needs to be run on the contents, which is (‘rectangular 3 . 4). The same magnitude procedure as before is called, which invoked apply-generic a second time. This time it sees the ‘(rectangular) tag and calls the magnitude procedure that was defined in install-rectangular-package on the contents, which is (3 . 4), and the result is 5.

2.78

```(define (attach-tag type-tag contents)
(if (number? contents)
contents
(cons type-tag contents)))

(define (type-tag datum)
(cond ((number? datum) 'scheme-number)
((pair? datum)(car datum))
(else (error "Bad tagged datum -- TYPE-TAG" datum))))

(define (contents datum)
(cond ((number? datum) datum)
((pair? datum) (cdr datum))
(else (error "Bad tagged datum -- CONTENTS" datum))))
```

Essentially we add a new condition in each procedure to deal with the special case when we’re dealing with a native number type. type-tag has to attach a scheme-number tag to keep the dispatch table happy.

2.79

Define procdures to deal with each data type and put them into the table. These are defined in their corresponding install procedures.

```(put 'equ? '(scheme-number scheme-number)
(lambda (x y) (= x y)))

(define (equ?-rational x y)
(= (/ (numer x) (denom x)) (/ (numer y) (denom y))))
(put 'equ? '(rational rational) equ?-rational)

(define (equ?-complex z1 z2)
(and (= (real-part z1) (real-part z2))
(= (imag-part z1) (imag-part z2))))
(put 'equ? '(complex complex) equ?-complex)
```

The generic operation also needs to be defined.

```(define (equ? a b) (apply-generic 'equ? a b))
```

2.80

Same thing is done as before in 2.79.

```(put '=zero? '(scheme-number)
(lambda (x) (= x 0)))

(put '=zero? '(rational) (lambda (x) (= 0 (numer x))))

(define (=zero?-complex z)
(and (= (real-part z) 0)
(= (imag-part z) 0)))
(put '=zero? '(complex) =zero?-complex)

(define (=zero? a) (apply-generic '=zero? a))
```

Comments:: Quite disappointed in my own progress lately. A mix of obligations for school/work and being unable to concentrate and understand what the chapter was talking about. One thing I’ve noticed about this book is that it requires a lot of concentration to understand the content even though it seems short and simple at first.