Clojure – alter

Clojure alter

In this guide, we will discuss 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]

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply