On Nov 14, 5:42 pm, André Thieme <splendidl...@googlemail.com> wrote: > But in real programs things are not so easy. We have refs in refs.
This is just a thought experiment. But what about actually having refs in refs? I'm not sure if I am reinventing mutable object here, so please shoot me down ;-) Clojure 1.1.0-alpha-SNAPSHOT user=> (deftype Person [name age friends] [clojure.lang.IPersistentMap]) #'user/Person user=> (def *persons* (ref {})) #'user/*persons* user=> (dosync (alter *persons* assoc :ethel (ref (Person "ethel" 24 [])))) {:ethel #<r...@585976c2: #:Person{:name "ethel", :age 24, :friends []} >} user=> (dosync (alter *persons* assoc :fred (ref (Person "fred" 42 [])))) {:fred #<r...@2c78bc3b: #:Person{:name "fred", :age 42, :friends []} >, :ethel #<r...@585976c2: #:Person{:name "ethel", :age 24, :friends []} >} user=> @*persons* {:fred #<r...@2c78bc3b: #:Person{:name "fred", :age 42, :friends []} >, :ethel #<r...@585976c2: #:Person{:name "ethel", :age 24, :friends []} >} ;;now... user=> (dosync (alter (:fred @*persons*) (fn [f] (assoc f :friends (conj (:friends f) (:ethel @*persons*)))))) #:Person{:name "fred", :age 42, :friends [#<r...@585976c2: #:Person {:name "ethel", :age 24, :friends []}>]} user=> @*persons* {:fred #<r...@2c78bc3b: #:Person{:name "fred", :age 42, :friends [#<r...@585976c2: #:Person{:name "ethel", :age 24, :friends []}>]} >, :ethel #<r...@585976c2: #:Person{:name "ethel", :age 24, :friends []} >} user=> (identical? (first (:friends @(:fred @*persons*))) (:ethel @*persons*)) true Note that Fred and Ethel are identities, and their corresponding refs still refer to *immutable* values (the refs themselves). Now to inc age: user=> (dosync (alter (:ethel @*persons*) update-in [:age] inc)) #:Person{:name "ethel", :age 25, :friends []} user=> @*persons* {:fred #<r...@da0225b: #:Person{:name "fred", :age 42, :friends [#<r...@7ae35bb7: #:Person{:name "ethel", :age 25, :friends []}>]} >, :ethel #<r...@7ae35bb7: #:Person{:name "ethel", :age 25, :friends []} >} In a way, I like the modeling: the people are actually identities and there are relations between identities. STM ensures consistent snapshots. So am I reinventing objects in a bad way, or is this just recognizing the true identities? :-) /K -- 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