Created
February 12, 2016 01:05
-
-
Save philipjkim/68169fc44aff2377eb26 to your computer and use it in GitHub Desktop.
Reversing nested sequences in Clojure
This file contains hidden or 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 my-reverse-v1 [input] | |
(let [head (first input) | |
tail (rest input)] | |
(if head | |
(conj (my-reverse-v1 (vec tail)) | |
(if (sequential? head) | |
(my-reverse-v1 (vec head)) | |
head)) | |
[]))) | |
(defn my-reverse-v2 [initial input] | |
(let [head (first input) | |
tail (rest input)] | |
(if head | |
(recur (cons (if (sequential? head) (my-reverse-v2 [] head) head) initial) tail) | |
(vec initial)))) | |
(defn test-my-reverse [] | |
(let [input [[1 2] 3 [4 [5 6]] 7 [8 [9 [10 11] 12]]] | |
expected [[[12 [11 10] 9] 8] 7 [[6 5] 4] 3 [2 1]]] | |
(println "my-reverse-v1:" (= expected (my-reverse-v1 input))) | |
(println "my-reverse-v2:" (= expected (my-reverse-v2 [] input))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment