Clojure-immutable-nature

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

Clojure-不変の自然

デフォルトでは構造も不変であるため、特定のキーの値を変更しようとしても変更されません。

これがどのように発生するかの例を、次のプログラムに示します。

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

上記の例では、「assoc」関数を使用して、構造内の従業員名に新しい値を関連付けます。

出力

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

John
John

これは、構造が不変であることを明確に示しています。 値を変更する唯一の方法は、次のプログラムに示すように、変更された値で新しい変数を作成することです。

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

出力

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

{:EmployeeName Mark, :Employeeid 1}