Created
July 23, 2012 07:36
-
-
Save ponkore/3162439 to your computer and use it in GitHub Desktop.
Clojure Programming Example 2-1. Implementation of a mutable integer in "Clojure"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Clojure Programming Chapter 2. Functional Programming | |
;;; Example 2-1. Implementation of a mutable integer in "Clojure" | |
(defprotocol IStatefulInteger | |
(setInt [this new-state]) | |
(intValue [this])) | |
(deftype StatefulInteger [^{:volatile-mutable true} state] | |
IStatefulInteger | |
(setInt [this new-state] (set! state new-state)) | |
(intValue [this] state) | |
Object | |
(hashCode [this] state) | |
(equals [this obj] | |
(and (instance? (class this) obj) | |
(= state (.intValue obj))))) | |
;;; | |
;;; P.55 example | |
;;; | |
user=> (def five (StatefulInteger. 5)) | |
;#'user/five | |
user=> (def six (StatefulInteger. 6)) | |
;#'user/six | |
user=> (.intValue five) | |
;5 | |
user=> (.intValue six) | |
;6 | |
user=> (= five six) | |
;false | |
user=> (.setInt five 6) | |
;6 | |
user=> (= five six) | |
;true | |
user=> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment