Sunil S Nandihalli <sunil.nandiha...@gmail.com> writes:

> Hello everybody,
> the following code is not producing what was expected of it in clojure
> 1.2 .. has this been fixed the clojure 1.3?
>
> (let [x (transient {})]
>   (dotimes [i 10]
>     (assoc! x i (* i i)))
>   (persistent! x))

This is not a bug, it's a misuse of transients.  A transient map is not
an imperative mutable map.  They're just a performance optimisation for
certain use cases of an immutable map.

To quote the clojure.org/transients documentation:

> Note in particular that transients are not designed to be bashed
> in-place. You must capture and use the return value in the next
> call. In this way, they support the same code structure as the
> functional persistent code they replace. 

There's a simple rule for using transients correctly.  First write the
code with a normal immutable data structure:

(let [x {}]
  (reduce (fn [m i] (assoc m i (* i i))) x (range 10)))

Then stick "!" on the end of assoc/conj/disj and wrap in the
transient/persistent! calls.  Don't make any other changes to the
code structure.

(let [x (transient {})]
  (persistent! (reduce (fn [m i] (assoc! m i (* i i))) x (range 10))))

Hope that helps,

Alex

-- 
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