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.

Syntax

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.

Example

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

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

Output

The above program produces the following output.

[John Mark]
clojure_reference_values.htm
Advertisements