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

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


  #^{: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 []) => [[]]とすべきか…"}
; ----
; ----
  (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)
            (recur cdr (list car) (cons tem acc))))))

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

comments powered by Disqus