Clojure - alter


This function is used to alter the value of a reference type but in a safe manner. This is run in a thread, which cannot be accessed by another process. This is why the command needs to be associated with a ‘dosync’ method always. Secondly, to change the value of a reference type, a function needs to be called to make the necessary change to the value.


Following is the syntax.

(alter refname fun)

Parameters − ‘refname’ is the name of the variable holding the reference value. ‘fun’ is the function which is used to change the value of the reference type.

Return Value − The reference and its corresponding new value.


An example on how this is used is shown in the following program.

(ns clojure.examples.example
(defn Example []
   (def names (ref []))
   (defn change [newname]
         (alter names conj newname)))
   (change "John")
   (change "Mark")
   (println @names))


The above program produces the following output.

[John Mark]