Clojure – commute

Clojure commute

In this guide, we will discuss Clojure Commute. Commute is also used to change the value of a reference type just like alter and ref-set. The only difference is that this also needs to be placed inside a ‘dosync’ block. However, this can be used whenever there is no need to know which calling process actually changed the value of the reference type. Commute also uses a function to change the value of the reference variable.

Syntax

Following is the syntax.

(commute 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 counter (ref 0))
   
   (defn change [counter]
      (dosync
         (commute counter inc)))
   (change counter)
   (println @counter)
   
   (change counter)
   (println @counter))
(Example)

Output

The above program produces the following output.

1
2

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply