Lisp - 常量



在 LISP 中,常量是指在程式執行過程中其值永不改變的變數。常量使用 **defconstant** 結構宣告。

語法

**defun** 結構用於定義函式,我們將在 **函式** 章節中詳細介紹。

(defconstant PI 3.141592)

示例 - 建立常量

以下示例演示了宣告全域性常量 PI,並在隨後名為 *area-circle* 的函式中使用該值計算圓的面積。

建立一個名為 main.lisp 的新原始碼檔案,並在其中輸入以下程式碼。

main.lisp

; define a constant PI as 3.141592
(defconstant PI 3.141592)

; define a function area-circle
(defun area-circle(rad)
   ; terminate current printing
   (terpri)
   ; print the redius
   (format t "Radius: ~5f" rad)
   ; print the area
   (format t "~%Area: ~10f" (* PI rad rad)))
   
; call the area-cirlce function with argument as 10
(area-circle 10)

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回結果。

Radius:  10.0
Area:   314.1592

我們可以使用 **boundp** 結構檢查常量是否已定義。

語法

; returns T if constant is available else return Nil
(boundp 'PI)

示例 - 檢查常量是否存在

以下示例演示了宣告全域性常量 PI,並隨後使用 boundp 結構檢查 PI 是否存在,在下一條語句中,我們檢查另一個未定義的常量。

建立一個名為 main.lisp 的新原始碼檔案,並在其中輸入以下程式碼。

main.lisp

; define a constant PI as 3.141592
(defconstant PI 3.141592)

; check if PI constant is defined
(write (boundp 'PI))  ; prints T

; terminate printing
(terpri) 

; check if OMEGA constant is defined
(write (boundp 'OMEGA))  ; prints Nil

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回結果。

T
NIL
廣告