You're viewing version 1.2.0 of ref. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16
  • (ref x)
  • (ref x & options)
Creates and returns a Ref with an initial value of x and zero or
more options (in any order):

:meta metadata-map

:validator validate-fn

:min-history (default 0)
:max-history (default 10)

If metadata-map is supplied, it will be come the metadata on the
ref. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception. validate-fn will be called on
transaction commit, when all refs have their final values.

Normally refs accumulate history dynamically as needed to deal with
read demands. If you know in advance you will need history you can
set :min-history to ensure it will be available when first needed (instead
of after a read fault). History is limited, and the limit can be set
with :max-history.

1 Example top

  • user=> (ref [])
    #<ref@5fafa486: []>
    
    user=> (ref 1 :validator pos?)
    #<Ref@6c484c6b: 1>
    
    => (ref 0 :validator pos?)
    IllegalStateException Invalid reference state  clojure.lang.ARef.validate (ARef.java:33)
    
    => (dosync (ref-set (ref 1 :validator pos?) 0))
    IllegalStateException Invalid reference state  clojure.lang.ARef.validate (ARef.java:33)
    
    => (dosync (ref-set (ref 1 :validator pos?) 2))
    2
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1723 top

(defn ref
  "Creates and returns a Ref with an initial value of x and zero or
  more options (in any order):

  :meta metadata-map

  :validator validate-fn

  :min-history (default 0)
  :max-history (default 10)

  If metadata-map is supplied, it will be come the metadata on the
  ref. validate-fn must be nil or a side-effect-free fn of one
  argument, which will be passed the intended new state on any state
  change. If the new state is unacceptable, the validate-fn should
  return false or throw an exception. validate-fn will be called on
  transaction commit, when all refs have their final values.

  Normally refs accumulate history dynamically as needed to deal with
  read demands. If you know in advance you will need history you can
  set :min-history to ensure it will be available when first needed (instead
  of after a read fault). History is limited, and the limit can be set
  with :max-history."
  {:added "1.0"}
  ([x] (new clojure.lang.Ref x))
  ([x & options] 
   (let [r  ^clojure.lang.Ref (setup-reference (ref x) options)
         opts (apply hash-map options)]
    (when (:max-history opts)
      (.setMaxHistory r (:max-history opts)))
    (when (:min-history opts)
      (.setMinHistory r (:min-history opts)))
    r)))
Vars in clojure.core/ref: defn let when

Comments top

No comments for ref. Log in to add a comment.