Ninety-Nine Lisp Problems – P09 の解答

Nov 22, 2010   #gauche  #Lisp  :

L-99: Ninety-Nine Lisp Problemsの問題を解答してみたよ。なんか、エレガントではないなぁ:

;; P09 (**) Pack consecutive duplicates of list elements into sublists.
;;     If a list contains repeated elements they should be placed in separate sublists.
;;     Example:
;;     * (pack '(a a a a b c c a a d e e e e))
;;     ((A A A A) (B) (C C) (A A) (D) (E E E E))
(define (pack-seed front sublist result l)
[(null? l) (append result (list sublist))]
[(eq? front (car l)) (pack-seed front
(append sublist
(list front))
(cdr l))]
[else (pack-seed (car l)
(list (car l))
(if (null? result)
(if (null? sublist)
(append result (list sublist)))
(append result (list sublist)))
(cdr l))]))
(define (pack l)
(pack-seed #f '() '() l))
(pack '(a a a a b c c a a d e e e e))