Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created September 14, 2011 04:46
Show Gist options
  • Save ghoseb/1215871 to your computer and use it in GitHub Desktop.
Save ghoseb/1215871 to your computer and use it in GitHub Desktop.
Flatten a nested collection using Tail Recursion.
(defn my-flatten
"Flatten a nested collection using Tail Recursion."
[coll]
(letfn [(step [[fst & more :as coll] res]
(if (seq coll)
(if (coll? fst)
(recur (concat fst more) res)
(recur more (cons fst res)))
(reverse res)))]
(step coll nil)))
;; (my-flatten [1 [2 [3 [4 [5 [6 [7] 8] 9] 10] 11] 12] 13])
;; => (1 2 3 4 5 6 7 8 9 10 11 12 13)
@ghoseb
Copy link
Author

ghoseb commented Sep 15, 2011

Thanks Srid :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment