Skip to content

Instantly share code, notes, and snippets.

@nivekuil
Created April 11, 2021 03:54
Show Gist options
  • Save nivekuil/fa4bd693f4906267ee956473e8050eaa to your computer and use it in GitHub Desktop.
Save nivekuil/fa4bd693f4906267ee956473e8050eaa to your computer and use it in GitHub Desktop.
merge two sorted vecs clojure
(defn merge-two-vecs
"Takes a keyfn and two sorted vecs, peek-smallest, and returns one sorted vec.
e.g. (merge-two-vecs identity [5 3 1] [6 4 2])"
[keyfn xs ys]
(let [keyfn (comp keyfn peek)]
(loop [acc (transient [])
xs xs
ys ys]
(let [x (keyfn xs) y (keyfn ys)]
(cond
(and (nil? x) (nil? y)) (persistent! acc)
(or (nil? y) (and x (<= 0 (compare x y)))) (recur (conj! acc (peek xs)) (pop xs) ys)
(or (nil? x) (and y (> 0 (compare x y)))) (recur (conj! acc (peek ys)) xs (pop ys)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment