Clojure - 變數



在 Clojure 中,變數 透過 ‘def’ 關鍵字定義。它有點不同,其中變數的概念更多地與繫結有關。在 Clojure 中,一個值繫結到一個變數。需要注意的一件關鍵事情是 Clojure 中的變數是不可變的,這意味著為了更改變數的值,需要銷燬它並重新建立。

以下是 Clojure 中基本型別的變數。

  • short - 用於表示短整型數字。例如,10。

  • int - 用於表示整數。例如,1234。

  • long - 用於表示長整型數字。例如,10000090。

  • float - 用於表示 32 位浮點數。例如,12.34。

  • char - 定義單個字元字面量。例如,‘/a’。

  • Boolean - 表示布林值,可以是真或假。

  • String - 是文字字面量,以字元鏈的形式表示。例如,“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)

注意 - 在以上語句中,由於大小寫敏感性,status 和 STATUS 是 Clojure 中定義的兩個不同的變數。

以上示例展示瞭如何使用下劃線字元定義變數。

列印變數

由於 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
廣告