
- LISP 教程
- LISP - 首頁
- LISP - 概述
- LISP - 環境
- LISP - 程式結構
- LISP - 基本語法
- LISP - 資料型別
- LISP - 宏
- LISP - 變數
- LISP - 常量
- LISP - 運算子
- LISP - 決策
- LISP - 迴圈
- LISP - 函式
- LISP - 謂詞
- LISP - 數字
- LISP - 字元
- LISP - 陣列
- LISP - 字串
- LISP - 序列
- LISP - 列表
- LISP - 符號
- LISP - 向量
- LISP - 集合
- LISP - 樹
- LISP - 雜湊表
- LISP - 輸入 & 輸出
- LISP - 檔案 I/O
- LISP - 結構體
- LISP - 包
- LISP - 錯誤處理
- LISP - CLOS (公共Lisp物件系統)
- LISP 有用資源
- Lisp - 快速指南
- Lisp - 有用資源
- Lisp - 討論
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
廣告