Arantium Maestum

プログラミング、囲碁、読書の話題

Clojureでマージソート2

とりあえずiterate版も貼っておく。

(defn merge
  ([col] col)
  ([[head1 & rest1 :as col1] [head2 & rest2 :as col2]]
   (cond (some empty? [col1 col2]) 
           (concat col1 col2)
         (< head1 head2)
           (lazy-seq (cons head1 (merge rest1 col2)))
         :else
           (lazy-seq (cons head2 (merge col1 rest2))))))

(defn merge-sort [col]
  (letfn [(f [col1] (->> col1 
                         (partition-all 2) 
                         (map #(apply merge %))))]
    (->> col
         (map vector)
         (iterate f)
         (filter #(= 1 (count %)))
         first
         first)))

merge-coupleというあまりよろしくない名前をなくせたのが一番嬉しい。あとforじゃなくて(map vector)になったのもグッド。あとは好みの問題か。recurでも読みやすかったように思うがどうだろうか。