Search code examples
loopsclojurecopying

Query about copying from 1 vector into another vector in Clojure


I am implementing merge sort in Clojure. Using my Java reference point, I need to create the equivalent of

for (int k = lo; k <= hi; k++) {
            aux[k] = a[k]; 
}

in Clojure.

Here is what I have already tried:

  1. Loop and recur which don't seem to look quite like a 'for' loop, leading me to believe that the functional approach would be something radically different.
  2. I also looked at the "for" macro which seems the closest to what I need, but the fact that jumped so many hoops to get to it, somehow makes me feel that I am not doing something the Clojure way.
  3. I started with something like (defn copy-vector [a aux] (doseq [k a] (swap! aux conj k))).

But that seems horribly complicated for something that should be simple and is probably not even doing what I need it to it EXACTLY. Any inputs/guidance on the Clojure way of doing this?


Solution

  • Here are some mergesort implementations in Clojure.

    [Spoiler warning: these are complete implementations. If you want to work through it yourself you might not want to look at these straight away.]

    https://codereview.stackexchange.com/questions/23627/mergesort-implementation-in-clojure

    https://gist.github.com/alco/2135276 (This second one includes links to several other implementations.)