Lispの問題 from 「L-99: Ninety-Nine Lisp Problems」

Sep 5, 2010   #gauche  #Lisp  :


;; 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)
[(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)
[(null? l) result]
[(eq? front (car l)) (temp front
(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))