#:g1: clojureでL-99 (P12 ランレングス圧縮 その3)

Posted 2008-09-30 04:13:00 GMT

packの結果を加工せずに直接作成せよという問題。
clojureのletは分割束縛の機能があるのでリスト分解 & 合成が楽です。

(defn 
  #^{:doc "P13 (**) Run-length encoding of a list (direct solution)."
     :test (do (test= (encode-direct []) [] )
               (test= (encode-direct [1]) [1] )
               (test= (encode-direct '(a a a a b c c a a d e e e e))
                      '((4 a) b (2 c) (2 a) d (4 e)))) }
; -------------
  encode-direct
; -------------
  ([coll]
     (if (empty? coll)
       []
       (loop [coll (concat coll (list (gensym))),
              tem (list 1 (gensym))
              acc [] ]
         (let [[car & cdr] coll, [cnt item] tem]
           (cond (empty? coll)
                 (rest (reverse acc))
                 ;; 
                 (= car item)
                 (recur cdr (list (+ 1 cnt) car) acc)
                 ;; 
                 :else
                 (recur cdr 
                        (list 1 car)
                        (cons (if (= 1 cnt)
                                item
                                tem)
                              acc))))))))

comments powered by Disqus