またまた頑張ってみました。letrecを使って、結果を渡しながらやっている。もしかしたら、継続で書き換えられる?
;; P07 (**) Flatten a nested list structure.
;; Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).
;; Example:
;; * (my-flatten '(a (b (c d) e)))
;; (A B C D E)
;; Hint: Use the predefined functions list and append.
(define (atom? l)
(and (not (pair? l))
(not (null? l))))
(define (my-flatten l)
(letrec ((temp (lambda (result l)
(cond
[(null? l) result]
[(atom? (car l)) (temp (append result
(list (car l)))
(cdr l))]
[else (temp (temp result (car l))
(cdr l))]))))
(temp '() l)))
(my-flatten '(a (b (c d) e)))
;; P08 (**) Eliminate consecutive duplicates of list elements.
;; If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
;; Example:
;; * (compress '(a a a a b c c a a d e e e e))
;; (A B C A D E)
(define (compress l)
(letrec ((temp (lambda (front result l)
(cond
[(null? l) result]
[(eq? front (car l)) (temp front
result
(cdr l))]
[else (temp (car l)
(append result (list (car l)))
(cdr l))]))))
(temp '() '() l)))
(compress '(a a a a b c c a a d e e e e))