Clojure-variables
提供:Dev Guides
Clojure-変数
Clojureでは、変数*は *‘def’ キーワードによって定義されます。 変数の概念がバインディングに関係している場合は少し異なります。 Clojureでは、値は変数にバインドされます。 Clojureで注意すべき重要な点の1つは、変数が不変であることです。つまり、変数の値を変更するには、その変数を破棄して再作成する必要があります。
Clojureの変数の基本タイプは次のとおりです。
- short -これは短い番号を表すために使用されます。 たとえば、10。
- int -これは整数を表すために使用されます。 たとえば、1234。
- long -これは、長い数値を表すために使用されます。 たとえば、10000090。
- float -32ビット浮動小数点数を表すために使用されます。 たとえば、12.34。
- char -これは単一の文字リテラルを定義します。 たとえば、「/a」。
- ブール-これはブール値を表し、trueまたはfalseのいずれかです。
- 文字列-これらは、文字のチェーンの形式で表されるテキストリテラルです。 たとえば、「Hello World」。
可変宣言
以下は、変数を定義する一般的な構文です。
構文
(def var-name var-value)
ここで、「var-name」は変数の名前、「var-value」は変数にバインドされた値です。
例
以下は、変数宣言の例です。
(ns clojure.examples.hello
(:gen-class))
;; This program displays Hello World
(defn Example []
;; The below code declares a integer variable
(def x 1)
;; The below code declares a float variable
(def y 1.25)
;; The below code declares a string variable
(def str1 "Hello")
;; The below code declares a boolean variable
(def status true))
(Example)
変数の命名
変数の名前は、文字、数字、およびアンダースコア文字で構成できます。 文字またはアンダースコアで始まる必要があります。 Clojureは、Javaが大文字と小文字を区別するプログラミング言語であるため、大文字と小文字は区別されます。
例
Clojureでの変数の命名の例を次に示します。
(ns clojure.examples.hello
(:gen-class))
;; This program displays Hello World
(defn Example []
;; The below code declares a Boolean variable with the name of status
(def status true)
;; The below code declares a Boolean variable with the name of STATUS
(def STATUS false)
;; The below code declares a variable with an underscore character.
(def _num1 2))
(Example)
注-上記のステートメントでは、大文字と小文字が区別されるため、ステータスとステータスはClojureで定義される2つの異なる変数です。
上記の例は、アンダースコア文字を使用して変数を定義する方法を示しています。
変数の印刷
ClojureはJVM環境を使用するため、「println」関数も使用できます。 次の例は、これを実現する方法を示しています。
例
(ns clojure.examples.hello
(:gen-class))
;; This program displays Hello World
(defn Example []
;; The below code declares a integer variable
(def x 1)
;; The below code declares a float variable
(def y 1.25)
;; The below code declares a string variable
(def str1 "Hello")
(println x)
(println y)
(println str1))
(Example)
出力
上記のプログラムは、次の出力を生成します。
1
1.25
Hello