Clojure - Adding a New Key to the Structure



Since structures are immutable, the only way that another key can be added to the structure is via the creation of a new structure. An example on how this can be achieved is 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 :EmployeeRank "A"))
   (println newemp))
(Example)

In the above example, we associate a new key called EmployeeRank to the structure, but by creating a new structure object.

Output

The above program produces the following output.

{:EmployeeName John, :Employeeid 1, :EmployeeRank A}
clojure_structmaps.htm
Advertisements