Clojure - Immutable Nature



By default structures are also immutable, so if we try to change the value of a particular key, it will not change.

Example

An example of how this happens is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (defstruct Employee :EmployeeName :Employeeid)
   (def emp (struct-map Employee :EmployeeName "John" :Employeeid 1))
   (println (:EmployeeName emp))
   
   (assoc emp :EmployeeName "Mark")
   (println (:EmployeeName emp)))
(Example)

In the above example, we try to use the ‘assoc’ function to associate a new value for the Employee Name in the structure.

Output

The above program produces the following output.

John
John

This clearly shows that the structure is immutable. The only way to change the value is to create a new variable with the changed value as shown in the following program.

Example

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (defstruct Employee :EmployeeName :Employeeid)
   (def emp (struct-map Employee :EmployeeName "John" :Employeeid 1))
   (def newemp (assoc emp :EmployeeName "Mark"))
   (println newemp))
(Example)

Output

The above program produces the following output.

{:EmployeeName Mark, :Employeeid 1}
clojure_structmaps.htm
Advertisements