SICP solution exercise 2.28

Solution for exercise 2.28 of SICP:

;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 nil '())
(define x (list (list 1 2) (list 3 4)))
x

(define (fringe x)
  (cond ((null? x) x)
        ((not (pair? x)) (list x))
        (else (append (fringe (car x)) (fringe (cdr x))))))

(fringe x)
;(1 2 3 4)

(fringe (list x x))
;(1 2 3 4 1 2 3 4)

(display '--------tests--------)
(newline)

; tests
(define y (list 1 2 3))
y
(fringe y)

(define z (list 1 (list 2 3)))
z
(fringe z)

(define p (list 1 2 (list 3 4 (list 5 6))))
p
(fringe p)

(define q (list 1 2 (list 3 4 (list 5 6)) (list 7 8 ) 9 10))
q
(fringe q)

(define c (list 1 2 3))
(define d (list 4 5 6))
(define e (list c d))
e
(fringe e)

This entry was posted in SICP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>