SICP 2.3 exercises

(list ‘a ‘b ‘c)
(a b c)

(list (list ‘george))

(cdr ‘((x1 x2) (y1 y2)))
((y1 y2))

(cadr ‘((x1 x2) (y1 y2)))
(y1 y2)

(pair? (car ‘(a short list)))

(memq ‘red ‘((red shoes) (blue socks)))

(memq ‘red ‘(red shoes blue socks))
(red shoes blue socks)


(define (equal?-2 a b)
  (if (and (or (null? a) (not (pair? a)))
           (or (null? b) (not (pair? b))))
      (eq? a b)
    (if (and (pair? a) (pair? b))
        (and (equal?-2 (car a) (car b))
             (equal?-2 (cdr a) (cdr b)))

‘something is synctactic sugar for (quote something). Therefore ”abracadabra also means (quote (quote abracadabra)) which is (quote abracadabra). Finally, (car (quote abracadabra)) is quote.


(define (deriv exp var)
  (cond ((number? exp) 0)
        ((variable? exp)
         (if (same-variable? exp var) 1 0))
        ((sum? exp)
         (make-sum (deriv (addend exp) var)
                   (deriv (augend exp) var)))
        ((product? exp)
           (make-product (multiplier exp)
                         (deriv (multiplicand exp) var))
           (make-product (deriv (multiplier exp) var)
                         (multiplicand exp))))
        ((exponentiation? exp)
         (make-product (exponent exp)
                       (make-exponentiation (base exp)
                                            (make-sum (exponent exp) -1))))
         (error "unknown expression type -- DERIV" exp))))

(define (exponentiation? x)
  (and (pair? x) (eq? (car x) '**)))

(define (base exp)
  (cadr exp))

(define (exponent exp)
  (caddr exp))

(define (make-exponentiation b e)
  (cond ((=number? e 0) 1)
        ((=number? e 1) b)
        (else (list '** b e))))

Trivial, which is the point of this exercise. The one catch is to remember to use make-sum instead of ‘-‘ in deriv so that it can handle variable exponents.

(define (augend s)
  (if (null? (cdddr s))
      (caddr s)
    (make-sum (caddr s) (cadddr s))))

(define (multiplicand s)
  (if (null? (cdddr s))
      (caddr s)
    (make-product (caddr s) (cadddr s))))

Not so trivial. The difficulty was figuring out which procedures needed to be changed. I personally had a lot of trouble coming to the correct conclusion.


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