Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created September 14, 2011 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)
@srid
Copy link

srid commented Sep 14, 2011

Good :-) Similar to mine:

(defn my-flatten
  "Flatten the list"
  [lst]
  (reverse
   (loop [[x & xs] lst
          result nil]
     (cond
      (nil? x) result
      (seq? x) (recur (concat x xs) result)
      :else    (recur xs (cons x result))))))

@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