0

I am trying to implement 'interleave' for myself but get a outOfMemoryError

my version should be same as:

(interleave [1 2] [3 4])

Here is the code:

(defn myInterleav [col1 col2]
  (loop [r []
         c1 (first col1)
         c2 (first col2)]
    (if (and c1 c2)
      (recur (conj (conj r c1) c2)
        (next col1)
        (next col2))
      r)))

(myInterleav [1 2] [3 4])

Version 2 as 'noisesmith' suggested to rebind args, but get nullPointer error.

(defn myIL2 [col1 col2]
  (loop [m  []
         [e1 & c1] col1
         [e2 & c2] col2]
    (if (and e1 e2)

      (recur (conj m e1 e2)
             c1
             c2)
      m
    )))
4
  • 1
    For (myIL2 [1 2] [3 4]), I get [1 3 2 4]. Commented Apr 2, 2015 at 6:22
  • Would (flatten (map list col1 col2)) do what you want - my thinking was that if you could take the corresponding items in each collection, join them in some way and then take the contents of the resulting collections as a whole, you'd get where you want to be. Almost certainly there's a better way, which I hope somebody will point out! Commented Apr 2, 2015 at 7:46
  • @CodeFarmer That should work unless false or nil is in one of your lists, I just updated my answer to fix that case. Commented Apr 2, 2015 at 14:04
  • @peter: flatten is a problem because of the case where you have lists as individual items in your input list. (apply mapcat list colls) is how I would implement this, but that doesn't really address his code. Commented Apr 2, 2015 at 14:05

1 Answer 1

4

Your function never returns if neither input is empty, because the bindings for col1 and col2 cannot change. You need to rework your loop to rebind to the next of the previous binding each time, rather than the next of the initial function input. Something like this should work:

  [...
  [e1 & c1] col1
  [e2 & c2] col2]
(if (and (seq col1) (seq col2))
    (recur (conj r e1 e2)
           c1
           c2)
...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.