"Meikel Brandmeyer" <m...@kotka.de> said:
> On May 31, 9:37 am, "Sina K. Heshmati" <s...@khakbaz.com> wrote:
> 
>> The atomic 'state' doesn't seem to be visible to the datatype methods. The
>> question is why?
>>
>> (defprotocol prot-a
>>   (op-a [self x y]))
>>
>> (let [state (atom 10)]
>>   (deftype t-a [member]
>>     prot-a
>>     (op-a [self x y]
>>       (+ (.member self) x y @state))))
>>
>> (def t-a-instance (t-a. 5))
> 
> Of course not. deftype defines a type and not an environment. It's
> methods are not closures. (And even if they were, your state would be
> the same for all instances.) You have to pass the state as an argument
> to the constructor.

Now it makes more sense. Thanks.

> (defprotocol prot-a ...)
> (deftype t-a [state member] ...)
> 
> (defn make-t-a [member] (t-a. (atom 0) member))
> 
> (def t-a-instance (make-t-a 5))

I'll pass.

> If you actually want the same state for instances, use a private var.
> 
> (defprotocol prot-a ...)
> (def ^{:private true} state (atom 0))
> (deftype t-a [member] ...)
> 
> (def t-a-instance (t-a. 5))

This is a pretty solution but I tested it and it doesn't work the way it 
should. That is, when I load [1] in a separate REPL, I can still see and 
(reset!) the allegedly private 'state'.

user=> (load-file "path/tp/datatype-01.clj")
#'foo.datatype-01/t-a-instance
user=> (ns PREFIX.datatype-01)
nil
foo.datatype-01 => (op-a t-a-instance 1 2)
18
foo.datatype-01 => state
#<a...@302e67: 10>
foo.datatype-01 => @state
10
foo.datatype-01 => (reset! state 13)
13
foo.datatype-01 => @state
13

Kind regards,
SinDoc

[1] 
http://github.com/sindoc/algorithms/blob/master/src/main/clojure/whiteboard/y2010/hide-adt-state/datatype-01.clj

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