目录

Clojure - 变量

在Clojure中, variables'def'关键字定义。 它有点不同,其中变量的概念更多地与绑定有关。 在Clojure中,值绑定到变量。 在Clojure中需要注意的一件事是变量是不可变的,这意味着为了使变量的值发生变化,需要将其销毁并重新创建。

以下是Clojure中的基本变量类型。

  • short - 用于表示短数字。 例如,10。

  • int - 用于表示整数。 例如,1234。

  • long - 用于表示长数字。 例如,10000090。

  • float - 用于表示32位浮点数。 例如,12.34。

  • char - 这定义了单个字符文字。 例如,'/ a'。

  • Boolean - 这表示一个布尔值,可以是true或false。

  • String - 这些是以String形式表示的文本文字。 例如,“Hello World”。

变量声明

以下是定义变量的一般语法。

语法 (Syntax)

(def var-name var-value)

其中'var-name'是变量的名称,'var-value'是绑定到变量的值。

例子 (Example)

以下是变量声明的示例。

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

命名变量 (Naming Variables)

变量的名称可以由字母,数字和下划线字符组成。 它必须以字母或下划线开头。 大写和小写字母是不同的,因为Clojure就像Java一样区分大小写的编程语言。

例子 (Example)

以下是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)

Note - 在上面的语句中,由于区分大小写,status和STATUS是Clojure中定义的两个不同的变量。

上面的示例显示了如何使用下划线字符定义变量。

打印变量 (Printing variables)

由于Clojure使用JVM环境,您还可以使用'println'函数。 以下示例显示了如何实现此目的。

例子 (Example)

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

输出 (Output)

上述程序产生以下输出。

1
1.25
Hello
↑回到顶部↑
WIKI教程 @2018