I came up with a way to do it, but I'm sure there's a simpler way.
Here's what I have:

(defn swap [coll i j]
  (let [li (min i j) ui (max i j)]
    (let [[pre-li post-li] (split-at li coll)]
      (let [[post-li-pre-ui post-li-post-ui] (split-at (- ui 1) (rest
post-li))]
        (concat
         pre-li
         (list (nth coll j))
         post-li-pre-ui
         (list (nth coll i))
         (rest post-li-post-ui))))))

Basically, I find the lower index and the upper index.  I then find
the elements in the collection that appear before the lower index, and
the elements that appear between the lower index and the upper index,
and the elements that appear after the upper index.  I then create a
new list that is the concatenation of these sublists, in order.  It's
sort of the definition of swap on an immutable data structure, but it
feels like an awful lot of code.

I considered using subvec:

http://clojure.org/api#toc548

But I didn't want to require that my input collection be a vector, or
convert it to one.  This the precursor to my implementing a heap data
structure, as a little toy application.

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to