Skip to content

Instantly share code, notes, and snippets.

@ponkore
Created July 23, 2012 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponkore/3162439 to your computer and use it in GitHub Desktop.
Save ponkore/3162439 to your computer and use it in GitHub Desktop.
Clojure Programming Example 2-1. Implementation of a mutable integer in "Clojure"
;;; 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