#:g1: clojureでL-99 (P09 連続して現われる要素を纏める)

Posted 2008-09-25 22:40:00 GMT

なんとなくコメントも付けてみました。どうやら、キーと値のペアなら何でも格納できるようなので、色々活用できるのかもしれません。

(defn
  #^{:doc "P09 (**) Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate sublists."
     :test (do (test= (pack []) [[]])
               (test= (pack [1]) [[1]])
               (test= (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))))
     :comment "(pack []) => []とすべきか、(pack []) => [[]]とすべきか…"}
; ----
  pack
; ----
  [coll]
  (loop [coll coll, tem [], acc [] ]
    (let [[car & cdr] coll]
      (cond (empty? coll) 
            (reverse (cons tem acc))
            ;;
            (or (= car (first tem)) (empty? tem))
            (recur cdr (cons car tem) acc)
            ;;
            :else
            (recur cdr (list car) (cons tem acc))))))

(:comment ^#'pack) ;=> "(pack []) => []とすべきか、(pack []) => [[]]とすべきか…"

comments powered by Disqus