Sunday, June 7, 2009

Ex-2.31

(define (tree-map proc tree)
(map
(lambda (x)
(if (pair? x)
(tree-map proc x) (proc x))) tree))
(define (square-tree tree)
(tree-map square tree))

Ex-2.30

;without using any higher order procedures
(define (square-tree tree)
(cond
((null? tree) '())
((list? (car tree))
(append (list (square-tree (car tree)))
(square-tree (cdr tree))))
(else
(cons (square (car tree))
(square-tree (cdr tree))))))

;using higher order procedures
(define (square-tree tree)
(map
(lambda (x)
(if (pair? x)
(square-tree x) (square x))) tree))

Ex-2.29

;a
(define (left-branch m)
(car m))
(define (right-branch m)
(cadr m))
(define (branch-length b)
(car b))
(define (branch-structure b)
(cadr b))

;b
;total weight of a mobile
(define (total-weight m)
(+ (branch-total-weight (left-branch m))
(branch-total-weight (right-branch m))))


;find total weight of a branch
(define (branch-total-weight b)
(if (pair? (branch-structure b))
(total-weight (branch-structure b))
(branch-structure b)))

;test
(define b1 (make-branch 1 2))
(define b2 (make-branch 1 3))
(define m1 (make-mobile b1 b2))
(define b3 (make-branch 1 5))
(define b4 (make-branch 1 m1))
(define m (make-mobile b3 b4))
(total-weight m)
;Value: 10

;c
(define (balanced? m)
(let ((lb (left-branch m))
(rb (right-branch m)))
(and
(branch-balanced? lb)
(branch-balanced? rb)
(=
(* (branch-length lb) (branch-total-weight lb))
(* (branch-length rb) (branch-total-weight rb))))))
;see if a branch has a mobile structure and its
;balanced, if it has weight then return true
(define (branch-balanced? b)
(if (pair? (branch-structure b))
(balanced? (branch-structure b))
#t))

;test
(define b1 (make-branch 1 2))
(define b2 (make-branch 1 3))
(define m1 (make-mobile b1 b2))
(define b3 (make-branch 1 5))
(define b4 (make-branch 1 m1))
(define m (make-mobile b3 b4))
(balanced? m)
;Value: #f
(define b2 (make-branch 1 2))
(define m1 (make-mobile b1 b2))
(define b4 (make-branch 1 m1))
(define m (make-mobile b4 b4))
;value: #t

;d
Since we abstracted out the details of how we select various component of mobile and branch, so only selectors need to change.
(define (left-branch m)
(car m))
(define (right-branch m)
(cdr m))
(define (branch-length b)
(car b))
(define (branch-structure b)
(cdr b))

Ex-2.28

(define (fringe tree)
(cond
((null? tree) '())
((pair? tree)
(append (fringe (car tree)) (fringe (cdr tree))))
(else (list tree))))


Used wishful thinking here. I thought like this, If we knew the fringes of left and right subtree then the answer would be to just append them and this does the trick :).

Ex-2.27

(define (deep-reverse l)
(define (iter a r)
(cond ((null? a) r)
((list? (car a))
(iter (cdr a) (cons (deep-reverse (car a)) r)))
(else (iter (cdr a) (cons (car a) r)))))
(iter l '()))

Ex-2.26

passed

Ex-2.25

(car (cdaddr '(1 3 (5 7) 9)))
(caar '((7)))
(cadadr (cadadr (cadadr '(1 (2 (3 (4 (5 (6 7)))))))))