Hello everybody,

Recently I was implementing Insertion Sort in Clojure and did that using 
transients:
--- cut ---
(defn- insert
  "Insert element from `idx` into correct position in transient vector 
`tv`."
  [tv idx]
  (let [current-value (get tv idx)]
    (loop [i idx v tv]
      (let [left-value (get v (dec i))]
        (if (and (pos? i)
                 (> left-value current-value))
          (recur (dec i) (assoc! v i left-value))
          (assoc! v i current-value))))))

(defn insertion-sort
  "Insertion sort using transients."
  [v]
  (let [size (-> v count dec)]
    (loop [i 1 tv (transient v)]
      (if (<= i size)
        (recur (inc i) (insert tv i))
        (persistent! tv)))))
--- cut ---

And have a few questions/concerns:
1. IIUC transients are for this purpose - to do controlled performance 
optimizations, right?
2. Imperative insertion sort has O(1) space requirement. Does transients 
version have the same property?
3. I read that transients should not be bashed in place, but have seen the 
following code, which seems to be only to be able to "bash in place":
(let [tv (atom (transient v))]
   (doseq [exrps]
      (reset! tv (assoc! tv k v)))
   (persistent! tv))
Is this approach idiomatic or should be avoided? To me it looks strange. My 
approach is to write non-transient version, then just add transient, ! to 
mutators, and persist result.

Thank you,
Przemysław

-- 
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
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to