Created
April 11, 2021 03:54
-
-
Save nivekuil/fa4bd693f4906267ee956473e8050eaa to your computer and use it in GitHub Desktop.
merge two sorted vecs clojure
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
(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