Skip to content

Instantly share code, notes, and snippets.

@stuartsierra
Created April 4, 2014 20:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartsierra/9982776 to your computer and use it in GitHub Desktop.
Save stuartsierra/9982776 to your computer and use it in GitHub Desktop.
Demonstrations of Clojure `concat` StackOverflow

Concat StackOverflow

Demonstrations of how clojure.core/concat can produce a StackOverflow.

Classic concat bomb

This is the most obvious case: A loop that builds up a sequence by concatenation.

I’ve seen this fairly often in application code, usually from less-experienced Clojure programmers. It’s easy to fix by forcing the sequence into a vector.

Experienced Clojure programmers have learned not to do this.

(defn build-lists
  "Returns a concatenated sequence of ranges."
  [n]
  (loop [i 0
         out nil]
    (if (> i n)
      out
      (recur (inc i)
             (concat out (range i))))))
(build-lists 6)
(first (build-lists 4000))
(pst *e)

@methylene
Copy link

Hi, I think I'm having this problem. Could you post the correct way to do it, too? Thanks!

@methylene
Copy link

Ok in my case I didn't care about the order the elements in the result, so I used this stack-safe function in place of concat:

(defn safe-concat [list list1]
  (loop [src list1
         target list]
    (if (seq src)
      (recur (rest src)
             (conj target (first src)))
      target)))

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