my attempt to do the exercises in sicp.

Wednesday, July 16, 2008

sicp exercise 2.28



;  Exercise 2.28. Write a procedure fringe that takes as argument a tree (represented as a list)
;  and returns a list whose elements are all the leaves of the tree arranged in left-to-right order.
;  For example,
;  (define x (list (list 1 2) (list 3 4)))
;  (fringe x)
;  (1 2 3 4)
;  (fringe (list x x))
;  (1 2 3 4 1 2 3 4)


(define (fringe input)
  (define (fringe-impl items result)
    (cond ((null? items) result)
          ((pair? items) (fringe-impl (car items) (fringe-impl (cdr items) result)))
          (else (cons items result))))
  (fringe-impl input (list)))

(define x (list (list 1 2) (list 3 4)))

(display x) (newline)
(display (fringe x)) (newline)

(display (list x x)) (newline)
(display (fringe (list x x))) (newline)

(define y (list  1 2 3 4 (list 6 7)))
(display y) (newline)
(display (fringe y)) (newline)

No comments: