Clojure-adding-key-to-structure

提供:Dev Guides
移動先:案内検索

Clojure-構造に新しいキーを追加する

構造は不変であるため、別のキーを構造に追加できる唯一の方法は、新しい構造を作成することです。 これを実現する方法の例を次のプログラムに示します。

(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)

上記の例では、EmployeeRankという新しいキーを構造に関連付けていますが、新しい構造オブジェクトを作成しています。

出力

上記のプログラムは、次の出力を生成します。

{:EmployeeName John, :Employeeid 1, :EmployeeRank A}