Last active
August 29, 2015 14:10
-
-
Save orb/e8e1d79004554cff9a35 to your computer and use it in GitHub Desktop.
merge ordered seqs example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; austin clojure meetup hacking | |
;; ---------------------------------------- | |
;; just merge 2 seqs | |
(defn merge2 [s1 s2] | |
(if (seq s1) | |
(when (seq s2) | |
(let [i1 (first s1) | |
i2 (first s2)] | |
(if (< i1 i2) | |
(cons i1 (lazy-seq (mergeseq (rest s1) s2))) | |
(cons i2 (lazy-seq (mergeseq s1 (rest s2))))))) | |
s2)) | |
;; ---------------------------------------- | |
;; merge N seqs | |
(defn index-of-min [colls] | |
(loop [best nil | |
best-index nil | |
colls colls | |
i 0] | |
(if (seq colls) | |
(if-let [n (first (first colls))] | |
(if (or (nil? best) (< n best)) | |
(recur n i (rest colls) (inc i)) | |
(recur best best-index (rest colls) (inc i))) | |
(recur best best-index (rest colls) (inc i))) | |
best-index))) | |
(defn mergen [colls] | |
(when-let [i (index-of-min colls)] | |
(cons (first (nth colls i)) | |
(lazy-seq (mergen (update-in colls [i] rest)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment