Skip to content

Instantly share code, notes, and snippets.

@orb
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save orb/e8e1d79004554cff9a35 to your computer and use it in GitHub Desktop.
Save orb/e8e1d79004554cff9a35 to your computer and use it in GitHub Desktop.
merge ordered seqs example
;; 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