SICP 全笔记

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)

fringe 也需要深度递归。深度递归的思路参见 练习 2.27

;; using append can always keep current lst as a list of atom
(define (fringe lst)
  (cond ((null? lst) '())
        ((pair? (car lst))
         (append (fringe (car lst))
                 (fringe (cdr lst))))
        (else
         (append (list (car lst))
                 (fringe (cdr lst))))))

;;; tests begin
(load "../testframe.scm")

(let ((x '((1 2) (3)))
      (y '(1 (2 3)))
      (z '((1 2) 3)))
  (assertequal? (fringe x)
                '(1 2 3))
  (assertequal? (fringe y)
                '(1 2 3))
  (assertequal? (fringe z)
                '(1 2 3)))