On May 28, 9:52 am, SinDoc <s...@khakbaz.com> wrote: > L.S., > > I was wondering if someone could point me to recent usage examples of > deftype, defrecord, and reify. Reading [1] helped a lot but it wasn't > particularly easy to find it since it's not linked from the sidebar.
I've used protocols and defrecords to implement Michael Nygaard's "Circuit-breaker" pattern. The circuit breaker is basically a state-machine, with transitions that occur on various events. To me, it was very natural to model the transition functions as a protocol (defprotocol CircuitBreakerTransitions "Transition functions for circuit-breaker states" (proceed [s] "true if breaker should proceed with call in this state") (on-success [s] "transition from s to this state after a successful call") (on-error [s] "transition from s to this state after an unsuccessful call") (on-before-call [s] "transition from s to this state before a call")) The states are then datatypes (records in this case) that are extended to reach this protocol, e.g., (defrecord ClosedState [#^TransitionPolicy policy #^int fail-count]) ... (extend ClosedState CircuitBreakerTransitions ...) Blog: http://blog.higher-order.net/2010/05/05/circuitbreaker-clojure-1-2/ Code: http://github.com/krukow/clojure-circuit-breaker > Specifically, what I'd like to know is: > > - How to define and access member data fields -also mutable in case > of deftype- to my ADTs. The example is there for immutable fields. Why do you need mutability? > - Whether I can refer to type instances -an equivalent to the 'this' > keyword in Java. The first argument to a protocol function corresponds to the "this" keyword in Java, e.g., (extend ClosedState CircuitBreakerTransitions ... :on-success (fn [{f :fail-count p :policy, :as s}] ;; note we can destructure the 'this' argument (s) (if (zero? f) s (ClosedState. p 0))) ...) > - How to define constructors. A single constructor is automatically defined for you. In my case with two params: (ClosedState. policy fail-count) If you need more flexibility, I believe you need gen-class, but I am unsure. > > Kind regards, > SinDoc > > [1]http://clojure.org/datatypes Hope that helps. Kind Regards, - Karl -- 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