--- title: 'Lispの問題 from 「L-99: Ninety-Nine Lisp Problems」' author: kazu634 date: 2010-09-05 wordtwit_post_info: - 'O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:5339;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}' categories: - gauche - Lisp ---

またまた頑張ってみました。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))